locked
How can I get Values from a set of Collections of KeyValuePairs with LINQ? RRS feed

  • Question

  • I have a custom LINQ provider.  I've defined a query with a projection (i.e. I SELECT.  When I collapse (/precipitate/whatever you call it when you cause to be run) the query, I get a bunch of custom collections of KeyValuePair<string, object>'s.

    What I'd like to do is, from that, get a bunch of objects for which the strings equal a particular value.  At the moment, I'm enumerating over the bunch of custom collections and, within that, enumerating over the collection of KeyValuePairs and adding to a list all of the objects where string = "x".  I feel that I ought to be able to do this in LINQ but I can't work out how.  I'm new to LINQ - I know there are loads of resources out there but I can't work out how to phrase the question so that my searches throw out the answer.

    I'll be grateful for any help you can give me.

    Wednesday, January 25, 2012 7:28 PM

Answers

  • If I have well undestood your goal, I think you can acheive it by doing this:

    IEnumerable<KeyValuePair<string, object>>[] bunch = new IEnumerable<KeyValuePair<string, object>>[]
    {
    	new Dictionary<string, object>(),
    	new Dictionary<string, object>(),
    	new Dictionary<string, object>(),
    };
    
    IEnumerable<object> result = bunch.SelectMany(collection => collection.Where(kvp => kvp.Key.Equals("searchedKey")).Select(kvp => kvp.Value));
    
    

    Jojo

     

     

    Thursday, January 26, 2012 7:32 AM

All replies

  • If I have well undestood your goal, I think you can acheive it by doing this:

    IEnumerable<KeyValuePair<string, object>>[] bunch = new IEnumerable<KeyValuePair<string, object>>[]
    {
    	new Dictionary<string, object>(),
    	new Dictionary<string, object>(),
    	new Dictionary<string, object>(),
    };
    
    IEnumerable<object> result = bunch.SelectMany(collection => collection.Where(kvp => kvp.Key.Equals("searchedKey")).Select(kvp => kvp.Value));
    
    

    Jojo

     

     

    Thursday, January 26, 2012 7:32 AM
  • Thanks for the reply: that's great!  If I .ToList() the original query it works exactly as I wanted.

    I did try just tacking your .SelectMany(etc.) onto the end of my query but it didn't work.  It seemed to cause the provider to ignore one of the other extension methods which changed the type of query that was being run.

    Friday, January 27, 2012 6:54 PM