CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: dictionary

  1. #1
    Join Date
    Oct 2010
    Posts
    11

    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.

  2. #2
    Join Date
    Jun 2008
    Posts
    2,477

    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.

  3. #3
    Join Date
    Aug 2008
    Posts
    902

    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
  •  





Click Here to Expand Forum to Full Width

Featured