作业:如何获取多个key集合?
我
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
,其他,经典的Dictionary
谢谢。
编辑:
用于输出。有 2 个字母“a”,由数组中索引“0”(第一个位置)上的 ID 9 标识。 “b”的索引为 1(输入数组中的第二个位置),“c”的索引为 2(第三个位置)。
编辑 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]
编辑 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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Lookup
可能是在这里使用的正确类 - 并且 LINQ 允许您使用ToLookup
。请注意,Lookup
是在 .NET 3.5 中引入的,而不是在 .NET 4 中引入的。话虽如此,目前还不清楚如何从输入到示例输出...
编辑:好的,现在我知道您在索引之后,您可能需要使用 Select 的重载,其中首先包含索引:
Lookup
is probably the right class to use here - and LINQ lets you build one withToLookup
. Note thatLookup
was introduced in .NET 3.5, not .NET 4.Having said that, it's not at all clear how you'd go from your input to your sample output...
EDIT: Okay, now that I understand you're after the index, you might want to use the overload of Select which includes an index first: