我有一个对象数组
List<Card> cardsOnTheScreen = new List<Card>(5);
每张卡都有enum Honurs字段,有14种荣誉(杰克,女王等)有没有人能帮我在屏幕上找到这些元素不止一次?输出应该是例如两种或更多同一种荣誉的卡片列表。
答案 0 :(得分:0)
解决方案您应该使用LINQ来查找或比较集合中的项目而不使用循环
List<Card> cardsOnTheScreen = new List<Card>(5);
List<Card> newList = cardsOnTheScreen.Where(obj => (Object with some condition));
之后,您将获得所需的新列表
答案 1 :(得分:0)
按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