2011-01-24 26 views
0

我已经作业:如何获取多个密钥集合?

public class Letter 
{ 
    public string Value; 
    public int Id; 

    public Letter(string val, int id) 
    { 
     this.Value = val; 
     this.Id = id; 
    } 
} 

我需要一种重复的字典(LookUp()?)为:

private something TestCollection() 
{ 
    List<Letter> inputList = new List<Letter> { 
     new Letter("a", 9), 
     new Letter("b", 5), 
     new Letter("c", 8), 
     new Letter("aIdentic", 9) 
    }; 

    // compare inputList by letter's ID(!) 
    // use inputList (zero based) INDEXES as values 

    // return something, like LookUp: { "a"=>(0, 3), "b"=>(1), "c"=>(2) }; 

} 

使用.NET 4

如何获取呢?

据我了解,有2个解决方案,一个从.NET 4,Lookup<Letter, int>,其他的,经典的一个Dictionary<Letter, List<int>>

感谢。

编辑:

对于输出。有两个字母“a”,由数组中的索引“0”(第一个位置)上的ID 9标识。 “b”有索引1(输入数组中的第二个位置),“c” - 索引2(第三个)。

编辑2

约翰溶液:

public class Letter 
    { 
     public string Value; 
     public int Id; 

     public Letter(string val, int id) 
     { 
      this.Value = val; 
      this.Id = id; 
     } 
    } 

    private void btnCommand_Click(object sender, EventArgs e) 
    { 
     List<Letter> inputList = new List<Letter> { 
      new Letter("a", 9), 
      new Letter("b", 5), 
      new Letter("c", 8), 
      new Letter("aIdentic", 9) 
     }; 

     var lookup = inputList.Select((value, index) => 
      new { value, index }).ToLookup(x => x.value, x => x.index); 

     // outputSomething { "a"=>(0, 3), "b"=>(1), "c"=>(2) }; 
     foreach (var item in lookup) 
     { 
      Console.WriteLine("{0}: {1}", item.Key, item.ToString()); 
     } 

    } 

输出(I期望不超过键):

//WindowsFormsApplication2.Form1+Letter: System.Linq.Lookup`2+Grouping[WindowsFormsApplication2.Form1+Letter,System.Int32] 
//WindowsFormsApplication2.Form1+Letter: System.Linq.Lookup`2+Grouping[WindowsFormsApplication2.Form1+Letter,System.Int32] 
//WindowsFormsApplication2.Form1+Letter: System.Linq.Lookup`2+Grouping[WindowsFormsApplication2.Form1+Letter,System.Int32] 
//WindowsFormsApplication2.Form1+Letter: System.Linq.Lookup`2+Grouping[WindowsFormsApplication2.Form1+Letter,System.Int32] 

EDIT 3等于

public override bool Equals(object obj) 
{ 
    if (obj is Letter) 
     return this.Id.Equals((obj as Letter).Id); 
    else 
     return base.Equals(obj); 
} 

public override int GetHashCode() 
{ 
    return this.Id; 
} 
+0

你最后一个例子,即字典字典有什么问题?你试过了吗?这听起来像你需要每个键的多个值,而不是每个值的多个键。 – 2011-01-24 15:50:53

+0

@chibacity:是的。字典中有多个键,因此每个键对应一组值。 – serhio 2011-01-24 15:54:33

回答

1

Lookup可能是在这里使用的正确类 - 而LINQ允许您使用ToLookup构建一个类。需要注意的是Lookup引入.NET 3.5中,没有.NET 4

话虽如此,它不是完全清楚你是如何从你输入到你的样本输出...

编辑:好的,现在我知道你在索引之后,你可能想要使用包含索引的Select的超载:

var lookup = inputList.Select((value, index) => new { value, index }) 
         .ToLookup(x => x.value.Id, x => x.index);