【发布时间】:2011-01-24 15:49:06
【问题描述】:
我有
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
如何获得?
据我了解,有两种解决方案,一种来自 .NET 4,Lookup<Letter, int>,另一种,经典的一种Dictionary<Letter, List<int>>
谢谢。
编辑:
用于输出。有 2 个字母“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());
}
}
输出(我预计不超过 3 个键):
//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]
编辑 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;
}
【问题讨论】:
-
你的最后一个例子有什么问题,即字典?你试过了吗?听起来您需要每个键多个值,而不是问题所暗示的每个值多个键。
-
@chibacity:是的。字典中有多个键,因此每个键对应一个值数组。
-
@serhio 列表字典是一个很好的解决方案。单个键可以引用包含多个项目的列表。
-
@chibacity:也许吧。问题是如何获得它:)
-
@serhio 恐怕“获得它”并不完全清楚。你到底有什么问题?
标签: .net linq collections