简体   繁体   English

如何根据ID从列表中进行不同选择?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM