[英]How can i have distinct selection from a list on the basis of id?
I have folowing list that but i want distinct rows on the basis of catID how can i achieve this? 我有以下列表,但是我想根据catID获得不同的行,我该如何实现呢?
lst.AddRange(
(from xx in this.FreeInstructionItems
select new selectedCustomization()
{
TypeName = CategoryType.SpecialInstruction,
CategoryName = xx.InstructionInfo.CatName,
ItemName = xx.InstructionInfo.Description,
SourceID = xx.InstructionInfo.InstructionId,
CatID = xx.InstructionInfo.CatID,
Items = GetAllFreeItemNames(CategoryType.SpecialInstruction, xx.InstructionInfo.CatID)
}
).ToList()
);
return lst;
MoreLINQ和DistinctBy优于所有GroupBy黑客:
return lst.DistinctBy(x => x.CatID);
GroupBy
使用CatID
属性并返回每个组的First
元素:
return lst.GroupBy(x => x.CatID).Select(g => g.First()).ToList();
You can do this: 你可以这样做:
var results =
(from xx in this.FreeInstructionItems
group xx by xx.InstructionInfo.CatID into g
let instrInfo = g.First().InstructionInfo
select new selectedCustomization()
{
TypeName = CategoryType.SpecialInstruction,
CategoryName = instrInfo.CatName,
ItemName = instrInfo.Description,
SourceID = instrInfo.InstructionId,
CatID = instrInfo.CatID,
Items = GetAllFreeItemNames(
CategoryType.SpecialInstruction,
instrInfo.CatID)
});
lst.AddRange(results);
lst.AddRange(this.FreeInstructionItems.GroupBy(x=>x.InstructionInfo.CatID)
.FirstOrDefault()
.SelectMany(x=> new selectedCustomization()
{
TypeName = CategoryType.SpecialInstruction,
CategoryName = x.InstructionInfo.CatName,
ItemName = x.InstructionInfo.Description,
SourceID = x.InstructionInfo.InstructionId,
CatID = x.InstructionInfo.CatID,
Items = GetAllFreeItemNames(CategoryType.SpecialInstruction, xx.InstructionInfo.CatID)
}).ToList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.