如何ToLookup()与多个索引?

时间:2013-03-31 20:58:52

标签: c# .net linq lambda lookup

考虑下面的C#Console应用程序代码,使用

如何修改它以替换该行:

foreach (Product product in productsByCategory[category])

代码行

foreach (Product product in productsByCategory[category][Id])

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace myQuestion
{
  class Program
  {
    static void Main(string[] args)
    {
      var products = new List<Product>
      {
        new Product { Id = 1, Category = "Garden", Value = 15.0 },
        new Product { Id = 1, Category = "Garden", Value = 40.0 },
        new Product { Id = 3, Category = "Garden", Value = 210.3 },
        new Product { Id = 4, Category = "Pets", Value = 2.1 },
        new Product { Id = 5, Category = "Electronics", Value = 19.95 },
        new Product { Id = 6, Category = "Pets", Value = 21.25 },
        new Product { Id = 7, Category = "Pets", Value = 5.50 },
        new Product { Id = 8, Category = "Garden", Value = 13.0 },
        new Product { Id = 9, Category = "Automotive", Value = 10.0 },
        new Product { Id = 10, Category = "Electronics", Value = 250.0 }
      };


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

      Console.ReadLine();
    }
  }

  public sealed class Product
  {
    public int Id { get; set; }
    public string Category { get; set; }
    public double Value { get; set; }
    public override string ToString()
    {
      return string.Format("[{0}: {1} - {2}]", Id, Category, Value);
    }
  }
}

更新
这是一个人为的例子,旨在学习C#ToLookup Method的概念。

作为参考,我在阅读the David Andres' answer to question "What is the point of Lookup?"之后来到了这个问题:

"A Lookup will map to potentially several values.  

Lookup["Smith"]["John"] will be a collection of size one billion."   

我想重现一下。

或者我明白错了?

2 个答案:

答案 0 :(得分:8)

不确定我是否正确了解您的需求,但为什么不能这样做:

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

或者使用匿名对象:

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);
}

这是Servy

附加解决方案的非常类似的问题

答案 1 :(得分:4)

我偶然发现了这个问题,上面写着“关闭它,因为我确认它是不可能的”,并对这个话题进行了大量的研究。我能得到的最接近的是:

Striving to get a lookup of lookups

事实证明这是不可能的,因为:

  1. 类型Lookup<T, T>没有构造函数,只能使用.ToLookup() LINQ扩展函数,
  2. 所述函数没有resultSelector的重载(如.GroupBy()那样),因此始终只返回IGrouping<TKey, TElement>
  3. 即使查找结果只是一个元素(另一个Lookup),也不可能省略第一个IGrouping。因此,每次调用“父级”.Single()后都需要拨打.First()(或.ToList()[0].ElementAt(0)Lookup),这是...臭并且绝望。

    但是

    使用嵌套Dictionary<T, T>

    可以实现访问元素的相同语法

    Got it with Dictionaries

    LINQPad C#代码已上传here