簡體   English   中英

如何基於2個屬性過濾列表?

[英]How to filter a list based on 2 properties?

我的代碼中有一個列表,我需要根據兩個條件過濾並返回特定的行。 有問題的列表是數據庫中模型的列表。 每個模型上都有兩個ID屬性,一個是數據表中的ID,並且是唯一的,另一個是我們用來標識組並且可以重復的ID。 我們將它們稱為ID和GroupID。 基本上,我希望結果列表中每個GroupID都只有一個,並且應該是ID最高(從數字上來說)的列表。 例如:

輸入:

List<MyModel> modelList = new List<MyModel>
modelList[0].ID = 1   modelList[0].GroupID = 5
modelList[1].ID = 2   modelList[1].GroupID = 5
modelList[2].ID = 3   modelList[2].GroupID = 6
modelList[3].ID = 4   modelList[3].GroupID = 6

所需輸出:

Models at indexes 1 and 3.

使用LINQ:

var items = (from model in modelList
             group model by model.GroupID into modelGroup
             select modelGroup.Max(i => i.ID)).ToList();

您要做的是先按ID對modelList進行排序,然后按GroupID對列表項進行分組,然后拉取具有最大Id值的項。

var result = modelList.OrderByDescending(x => x.ID).GroupBy(x => x.GroupID).Select(x => x.First());

上面的查詢將為您提供結果。

var newModelList = modelList.GroupBy(ml => ml.GroupID)
.Select(g => new MyModel
{
    ID = g.OrderByDescending(x => x.ID).First().ID,
        GroupID = g.Key
}).ToList();

細節

1)然后Select GroupBy以通過GroupID獲得不同的項目。

2)在OrderByDescending之后的First()獲得最高ID

3) Select new MyModel只是為了明確顯示投影。

您可以嘗試使用GroupBy

var q = modelList.GroupBy(x => x.GroupID, x => x, 
                             (key, g) => new { 
                                             GroupID = key, 
                                             Id = g.Max(c => c.ID)
                                           });

這應將所有元素按GroupId分組,然后在該組之一中選擇Max ID

試試這個代碼:

List<MyModel> modelList = new List<MyModel>();
modelList.Add(new MyModel());
modelList.Add(new MyModel());
modelList.Add(new MyModel());
modelList.Add(new MyModel());

modelList[0].ID = 1; modelList[0].GroupID = 5;
modelList[1].ID = 2; modelList[1].GroupID = 5;
modelList[2].ID = 3; modelList[2].GroupID = 6;
modelList[3].ID = 4; modelList[3].GroupID = 6;

var list = from ml in modelList group ml by ml.ID into r select new { ID = r.Key, MaxGroupID = r.Max() };

這可能會幫助您modelList.GroupBy(model => model.GroupId, g => g.Id).Select(item => item.Max())

這是您的解決方案:

var myData = models.GroupBy(model => model.GroupId)
                   .Select(group => group.OrderByDescending(model => model.Id).First());

或者,您也可以這樣做:

var myData = models.GroupBy(model => model.GroupId)
                   .Select(group => group.First(model => model.Id == group.Max(model1 => model1.Id)));

為了好玩, 這里有個小提琴。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM