我如何才能根据id从列表中进行不同的选择
本文关键字:选择 列表 id | 更新日期: 2023-09-27 18:26:31
我有下面的列表,但我想要基于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();
您可以这样做:
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());