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;
}
你最后一个例子,即字典字典有什么问题?你试过了吗?这听起来像你需要每个键的多个值,而不是每个值的多个键。 – 2011-01-24 15:50:53
@chibacity:是的。字典中有多个键,因此每个键对应一组值。 – serhio 2011-01-24 15:54:33