我有
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(是第三个)。
John解决方案:
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]
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 :(得分: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);