【问题标题】:Compare all items from List and return in new list比较 List 中的所有项目并在新列表中返回
【发布时间】:2015-09-18 08:53:59
【问题描述】:

我有一个对象数组

List<Card> cardsOnTheScreen = new List<Card>(5);

每张卡片都有枚举荣誉字段,有 14 种荣誉(Jack、Queen 等)。谁能帮我找出哪些元素在屏幕上不止一次?输出应该是例如两个或多个相同荣誉的卡片列表。

【问题讨论】:

  • 你需要GroupBy & Count。最好尝试一下,而不是对您的问题提出完整的答案。

标签: c# linq list compare


【解决方案1】:

Honurs分组,按计数过滤,然后从组中获取卡片:

var result = cardsOnTheScreen
    .GroupBy(c => c.Honurs)
    .Where(g => g.Count() > 1)
    .SelectMany(g => g);

这是一个例子。假设我们有这样的设置:

public enum Honours { Ace, One, Jack, Queen, King }
public enum Suit { Clubs, Diamonds, Hearts, Spades }

public class Card
{
    public Honours Honours { get; set; }
    public Suit Suit { get; set; }
}

然后我们有一个充满卡片的列表:

List<Card> cardsOnTheScreen = new List<Card>
{
    new Card { Honurs = Honurs.Ace, Suit = Suit.Clubs },
    new Card { Honurs = Honurs.Ace, Suit = Suit.Hearts },
    new Card { Honurs = Honurs.Ace, Suit = Suit.Spades },
    new Card { Honurs = Honurs.One, Suit = Suit.Clubs },
};

使用上面的代码,将给出以下输出:

Ace, Clubs
Ace, Hearts
Ace, Spades

【讨论】:

  • 感谢它的工作!如果有两对,例如 Ace、Ace 和 King,King 将产生结果。Count == 4?里面有这 4 件物品吗?
  • 是的,它将有 4 个项目,试试吧!
【解决方案2】:

您应该使用 LINQ 来查找或比较集合中的项目而不使用循环的解决方案

List<Card> cardsOnTheScreen = new List<Card>(5);
List<Card> newList = cardsOnTheScreen.Where(obj => (Object with some condition));

之后你会得到你想要的新列表

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-31
    • 1970-01-01
    • 2020-07-07
    相关资源
    最近更新 更多