From: mickieparis on
I need linq help. I have a dictionary where the keys are strings and
I need to select from that dictionary into another dictionary where
the first two characters of the key match a parameter.

For exmaple here is the code:
Dictionary<string, string> origDict = new Dictionary<string,
string>();
origDict.Add(""BSOne", "1")
origDict.Add(""BSTwo", "2")
origDict.Add(""PLOne", "11")
origDict.Add(""PLTwo", "22")

I need to select into a new dictionary only where the keys start with
"BS"

The following code is in a method where prefix is being passed in as
"BS"
return oDict.ToDictionary(k => k.Key, v => v.Value, new
KeyComparer(prefix));


Then I created a KeyComparer Class - a totaly hack...
The code doesn't even go into the Equals method.
It's a total hack notice I don't even use the y parameter in the
Equals method.

public class KeyComparer : IEqualityComparer<string> {
private string sPrefix = "";
public KeyComparer(string sPrefix) {
this.sPrefix = sPrefix;
}

public bool Equals(string x, string y) {
return x.Substring(0,2) == this.sPrefix;
}
public int GetHashCode(string obj) {
return obj.ToString().GetHashCode();
}
}

I know I screwed this all up. :( I learn much better thru example and
I know there MUST be a better way. I’d really appreciate any help.
Thanks

Michelle
From: Arne Vajhøj on
On 23-04-2010 16:05, mickieparis wrote:
> Dictionary<string, string> origDict = new Dictionary<string,
> string>();
> origDict.Add(""BSOne", "1")
> origDict.Add(""BSTwo", "2")
> origDict.Add(""PLOne", "11")
> origDict.Add(""PLTwo", "22")
>
> I need to select into a new dictionary only where the keys start with
> "BS"
>
> The following code is in a method where prefix is being passed in as
> "BS"
> return oDict.ToDictionary(k => k.Key, v => v.Value, new
> KeyComparer(prefix));

There must be many solutions.

This is one of them:

Dictionary<string, string> d2 = d1.Where(kvp =>
kvp.Key.StartsWith("BS")).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

Arne
From: mickieparis on
Excellent work Arne! Works great! Thanks.

Michelle