2013-03-31 50 views
3

考慮到下面的C#控制檯應用程序的代碼,使用如何ToLookup()與多個索引?

我應該如何修改它,以替代線路:由代碼行

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

foreach (Product product in productsByCategory[category]) 

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." 

我想重現它。

或者我明白了嗎?

回答

6

不知道我正確地瞭解您的需求,但爲什麼你就不能這樣做:

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

+0

你可以在我的問題結尾查看「更新:」嗎? – Fulproof

+0

以前看過那些代碼片段和答案。關閉它是爲了證實我不可能擁有多個(自定義)索引(儘管在「查找」中有複合(來自自定義類或'Tuple') – Fulproof

1

我已經偶然發現了這個問題,閱讀「關閉它作爲證實給我,它是不可能「,並對該主題進行了大量研究。我能得到的最接近的是這樣的:

Striving to get a lookup of lookups

事實證明這不能因爲做:

  1. 沒有具有構造Lookup<T, T>類型,一次只能用.ToLookup() LINQ擴展功能,
  2. 上述函數沒有與resultSelector(如.GroupBy()一樣)的超載,因此始終只返回IGrouping<TKey, TElement>

即使查找的結果是隻有一個元素(另一個Lookup),則不可能以省略第一IGrouping。因此,在每次致電「父母」Lookup後,都需要致電.Single()(或.First().ToList()[0].ElementAt(0)),這是......臭和絕望。

用於訪問元件同樣的語法可以具有嵌套Dictionary<T, T>來代替實現:

Got it with Dictionaries

LINQPad C#代碼上傳here