views:

46

answers:

2

Hi All,

I have a generic dictonary which is templated in the following manner:

Dictionary<object, IList<ISomeInterface>> dictionary1 = new Dictionary<object,    IList<ISomeInterface>>();

If I wanted to omit certain list items against arbitrary keys (that is the items that are in the list contained within the value part of each of the key value pairs making up the dictionary) given some arbitrary condition (lets say omitting list items where a list item contained the string "abc")

I would expect to able to create/project into a new dictionary which would contain entries which contained lists WITHOUT those items whose name contained "abc"

How do I achieve this using a Lambda expression?

I was trying something like this:

var result1 = dictionary1.Where(x => x.Value == x.Value.Select(y => !y.contains("abc"));

+1  A: 

To you want it as another dictionary? Try this:

var result = original.ToDictionary(
    pair => pair.Key, // Key in result is key in original
    value => pair.Value  // Value in result is query on original value
                 .Where(item => !item.Contains("abc").ToList());

EDIT: VB as per the comment:

someDictionary.ToDictionary(Function(x) x.key, _ 
            Function(y) y.Value.Where(not y.Value contains("abc").ToList())
Jon Skeet
Yes, I would like it in another dictionary. I am going to test this very shortly.
brumScouse
Sorry Im in VB not C#
brumScouse
Then why have you posted C# source in your question? Anyway, this should translate reasonably easily to VB - it'll just be a bit uglier due to the more verbose lambda syntax in VB.
Jon Skeet
I was POCing in C# but to be fair to myself I did tag it as VB.NET. I have tried transposing to Vb.net but to no avail....
brumScouse
Ok, sorted. Not as messy as first thought. Thankyou for your help.
brumScouse
Thus transposed to Vb.net...someDictionary.ToDictionary(Function(x) x.key, _ Function(y) y.Value.Where(not y.Value contains("abc").ToList())
brumScouse
A: 
var result1 = dictionary1.Select(x => 
     {
          return new KeyValuePair<object, IList<ISomeInterface>>(
                     x.Key, 
                     x.Value.Where(y => y.Contains("abc")).ToList());
     }).ToDictionary(item => item.Key, item => item.Value);
Grizzly
Why bother calling Select first and then ToDictionary when you can do it all more simply in one call to ToDictionary?
Jon Skeet