简体   繁体   English

从集合LINQ(C#)中的第一组中选择项目

[英]select items from first group in collection LINQ (C#)

I create card game in c# and i have following class, containing PlayerIDs, card sets from each player and two most powerfull cards: 我用C#创建纸牌游戏,并且有以下课程,其中包含玩家ID,每个玩家的卡组以及两张功能最强大的卡:

public class ResultsList
{
    public int PlayerID = -1;
    public int Set = -1;
    public int Figure1 = -1;
    public int Figure2 = -1;
}

program creates list of results: 程序创建结果列表:

List<ResultsList> Results = new List<ResultsList>();

and next sorts it by Set, next by Figure1 and next by Figure2, so i get follownig list (example): 然后按Set对其进行排序,然后按Figure1和Figure2进行排序,因此我得到了关注列表(示例):

PlayerID       Set       Figure1         Figure2
0              2         2               1
1              2         2               1
3              1         1               0

It means that players "0" and "1" have same sets and figures, I want to put them both IDs in new list 这意味着玩家“ 0”和“ 1”具有相同的设置和数字,我想将他们两个ID都放入新列表中

List<int> Winers= new List<int>();

But in following case, "0" is the only one winner: 但在以下情况下,“ 0”是唯一的获胜者:

PlayerID       Set       Figure1         Figure2
0              2         3               1
1              2         2               1
3              1         1               0

So I want put only that ID into the results. 因此,我只想将该ID放入结果中。
How do I do that? 我怎么做?

After Results is ordered, you can use First to get the winner and then use TakeWhile to get all equal to it: 在订购了Results后,您可以使用“ First获得获胜者,然后使用“ TakeWhile获得与它相等的全部:

var winner = Results.First()
var winners = Results.TakeWhile(r => r.Set == winner.Set && r.Figure1 == winner.Figure1 && winner.Figure2 == r.Figure2).ToList();

You can achive this with GroupBy : 您可以使用GroupBy实现此目的:

List<ResultsList> winners = 
    results.GroupBy(r => new {Set = r.Set, Figure1 = r.Figure1, Figure2 = r.Figure2}).
    OrderBy(g => g.Key.Set).
    ThenBy(g => g.Key.Figure1).
    ThenBy(g => g.Key.Figure2).
    First().ToList();

If results is already ordered you may ommit the OrderBy and ThenBy clauses. 如果已经订购了results则可以省略OrderByThenBy子句。

List<ResultsList> items = Results.OrderByDescending(item1 => 
        item1.Set).ThenByDescending(item2 => item2.Figure1).ThenByDescending(item3 =>
            item3.Figure2).ToList();

        ResultsList winner = items[0];
        List<int> winners = new List<int>();
        winners.Add(winner.PlayerID);
        winners.AddRange(items.Where((item, index) => 
            index > 0 && item.Set == winner.Set && 
            item.Figure1 == winner.Figure1 && 
            item.Figure2 == winner.Figure2)
            .ToList().Select(item=>item.PlayerID));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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