.NET 4,我有
public class Humi
{
public int huKey { get; set; }
public string huVal { get; set; }
}
在另一个类中,这是一个方法中的代码:
IEnumerable<Humi> someHumi = new List<Humi>(); //This is actually ISingleResult that comes from a LinqToSql-fronted sproc but I don't think is relevant for my question
var humia = new Humi { huKey = 1 , huVal = "a"};
var humib = new Humi { huKey = 1 , huVal = "b" };
var humic = new Humi { huKey = 2 , huVal = "c" };
var humid = new Humi { huKey = 2 , huVal = "d" };
我想创建一个单一的 IDictionary <int,string[]>
,键 2 包含 ["C","D"]
谁能指出使用 Linq 进行转换的体面方法?
谢谢。
var myDict = someHumi
.GroupBy(h => h.huKey)
.ToDictionary(
g => g.Key,
g => g.ToArray())
创建一个IEnumerable<IGrouping<int, Humi>>
,然后将其投影到字典中。注意 .ToDictionary
返回字典,而不是 IDictionary。
您可以使用 ToLookup() 它允许每个键保存多个值,这正是您的场景(请注意,每个键将保存IEnumerable<string>
值,但不是数组):
var myLookup = someHumi.ToLookup(x => x.huKey, x => x.huVal);
foreach (var item in myLookup)
{
Console.WriteLine("{0} contains: {1}", item.Key, string.Join(",", item));
}
输出:
1 包含:a,b
2 包含:C,D