How ToLookup() with multiple indexes?

自作多情 提交于 2019-12-05 14:53:58
mipe34

Not sure I understand your needs correctly, but why can't you just do:

foreach (Product product in productsByCategory[category].Where(x=> x.Id == Id))

Or with an anonymous object:

var productsByCategory = products.ToLookup(p => new { p.Category, p.Id });
string category = "Groceries";
int Id = 1;
foreach (Product product in productsByCategory[new {Category = category, Id= Id}])
{
    Console.WriteLine("\t" + product);
}

Here is very similar question with additional solution by Servy

I've stumbled upon this question, read "closing it as being confirmed to me that it is impossible" and made a hefty research on the topic. The closest I could get to was this:

Turns out this can't be done because:

  1. There is no constructor for type Lookup<T, T>, one can only use .ToLookup() LINQ extension function,
  2. Said function doesn't have an overload with resultSelector (like .GroupBy() does) and thus always only returns IGrouping<TKey, TElement>.

Even if the result of the lookup is just one element (another Lookup), there is no possibility to omit the first IGrouping. So the call to .Single() (or .First() or .ToList()[0] or .ElementAt(0)) is required after each call to "parent" Lookup, which is... smelly and desperate.

But

The same syntax for accessing elements can be instead achieved with nested Dictionary<T, T>:

LINQPad C# code uploaded here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!