-
October 27th, 2010, 06:27 PM
#1
dictionary
Hello,
I have a dictionary d of type <string, list<int>>.
I'd like to remove a specific int from all the lists of the dictionary whose keys verify a specific condition (if s == 'hello' then remove 3 from d[s], for all the strings s of the dictionary d).
What's the easiest and shortest way to do that, in one line/instruction if possible ?
Thanks.
-
October 27th, 2010, 06:44 PM
#2
Re: dictionary
Why do you care about how many lines it takes? That's irrelevant. What is relevant is finding the best solution to a problem, whether that is 1 or 100 lines.
Anyway, the problem as stated is very simple. I am still stuck on .NET 2.0 at work, so I am not familiar with all of the new stuff. Anyhow, it will accomplish the same thing. All you need is a loop or two and some if statements to compare values.
-
October 27th, 2010, 08:02 PM
#3
Re: dictionary
I'm not a great C# coder and I have little experience with Dictionaries and other generic containers, but just the same it took me about 5 minutes to come up with this solution.
I don't know how elegant it is (or efficient), but it meets your criteria of fitting on one line
Code:
var d = new Dictionary<string, List<int>>();
d.Add("this", new List<int>(){ 1, 13, 42 });
d.Add("is a", new List<int>() { 1, 13, 42 });
d.Add("test!", new List<int>() { 1, 13, 42 });
d.Keys.ToList().FindAll((str) => str.Length == 5).ForEach((str) => d[str].RemoveAll((number) => number == 42));
This will remove the number 42 from every List who's Key is 5 characters long.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|