我是Linq的新手。我想知道这是最好的方式,还是有其他方法可以做到这一点。
我有一个要求,从Web服务,我收到一个项目列表:
class Item {
string ItemName { get; set;}
string GroupName { get; set; }
}
我收到以下数据:
ItemName: Item1; GroupName: A
ItemName: Item2; GroupName: B
ItemName: Item3; GroupName: B
ItemName: Item4; GroupName: A
ItemName: Item5; GroupName: A
现在,我希望获取列表中的所有唯一组,并将所有项目关联到该组。所以我上了课:
class Group {
string GroupName { get; set; }
List<string> Items { get; set; }
}
因此,只有一个组,所有关联的项目都将在列表下。
我做了两个LINQ语句:
var uniqueGroups = (from g in webservice
where g.Group != null
select g.GroupName).Distinct();
然后我循环了
foreach (var gn in uniqueGroups)
{
var itemsAssociated = (from item in webservice
where item.GroupName = gn.ToString()
select new {
});
}
然后我收到了这些物品,并将它们保存到我的物体中。
这是最好的方法吗?还是有任何LINQ语句可以一次完成所有这些?
感谢。
答案 0 :(得分:5)
听起来像你想要GroupBy
var itemsByGroup = items.GroupBy(i => i.GroupName);
foreach (var group in itemsByGroup)
{
var groupName = group.Key;
var itemsForThisGroup = group;
foreach (var item in itemsForThisGroup)
{
Console.Out.WriteLine(item.ItemName);
}
}
答案 1 :(得分:3)
你可以试试这个:
//List<Item> webservice = list with items from your webservice
var result = (from i in items
group i by i.GroupName into groups
select new Group()
{
GroupName = groups.Key,
Items = groups.Select(g => g.ItemName).ToList()
}).ToList();
答案 2 :(得分:1)
可以使用anonymous type和Enumerable.GroupBy
:
var groupItems =
webservice.Where(i => i.GroupName != null)
.GroupBy(i => i.GroupName)
.Select(grp => new { Group = grp.Key, Items = grp.ToList() });
foreach (var groupItem in groupItems)
Console.WriteLine("Groupname: {0} Items: {1}"
, groupItem.Group
, string.Join(",", groupItem.Items.Select(i => i.ItemName)));
区别是无用的,因为GroupBy
将始终使组不同,这是组的性质。
这是运行代码:http://ideone.com/R3jjZ
答案 3 :(得分:1)
我会用:
webservice.ToLookup(k => k.GroupName);
这将消除额外课程的需要。
希望这有帮助!