简体   繁体   中英

Merging two IQueryables into a Dictionary with LINQ

I have an IQueryable and want to stuff that into a Dictionary that has the Foo as the key, and the count of that Foo's Bars collection as the value.

public class Foo
{
    public string ID { get; set; }
    public ICollection<Bar> Bars { get; set; }
}

So the output would look something like this:

new Dictionary<Foo, int>
{
    { someFoo, 2 },
    { anotherFoo, 6 },
    ...
}

And I need to do this straight from the IQueryable, without iterating over the actual objects. To be clear, I do not want to do this:

// given some IQueryable<Foo> called 'foos' and some Dictionary<Foo, int> called 'dictionary'
foreach (var foo in foos.ToList())
{
    dictionary.Add(foo, foo.Bars.Count());
}

Things I've tried that didn't work

METHOD 1

var dictionary = foos.ToDictionary(key => key, value => foos.Select(foo => foo.Bars.Count));

METHOD 2

var counts = foos.Select(foo => foo.Bars.Count);

for (var i = 0; i < foos.Count(); i++)
{
      dictionary.Add(foos.ElementAt(i), counts.ElementAt(i));
}

我很确定这会奏效,您是否尝试过以下方法:

var dictionary = foos.ToDictionary(foo => foo, foo => foo.Bars.Count());

Ah, this ended up working:

var result = from foo in foos
             select new
             {
                 Foo = foo,
                 Count = foo.Bars.Count()
             };

That method also has the added benefit of letting my specify the names of the field, which is nice for when I serialize this object to JSON.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM