开发者

LINQ query gone wrong

I have a class Card that holds a reference to an enum with different Card types. The enum is defined as follows:

 enum Rank
    {
        Ace = 1,
        Two,
        Three,
        Four,
        Five,
        Six,
        Seven,
        Eight,
        Nine,
        Ten,
        Jack,
        King,
        Queen
    }

I have a LINQ Query that is supposed to take a List and check if they are in sequence. So that means the difference between any two ranks is only 1.

Query:

List<Card> cards = group.ToList();
cards.Sort(SortComparatorByRank);
List<Card> test = cards.Where((x, idx) =>
            (idx >= 1 && (int)cards[idx - 1].CardRank == (int)x.CardRank - 1 ||
            (idx < cards.Count() - 1 &&
            (int)cards[id开发者_JAVA技巧x + 1].CardRank == (int)x.CardRank + 1))).ToList();

However running this, I get this result:

LINQ query gone wrong

As you can see, Two and Four supposedly follow each other???

The list given to this query does not contain all cards, thats why I need to check the ranking order, etc...


No, that doesn't show that Two and Four supposedly follow each other. It suggests that Three wasn't present in cards.

Two passes the first part of the filter due to Ace coming before it, and Four passes the second part of the filter due to Five coming after it.

Given that you're trying to check whether everything's in sequence, it sounds like you really want something returning a bool - for which I'd suggest All. You also only want them pairwise, so I'd consider something like:

var valid = cards.Zip(cards.Skip(1), (first, second) => new { first, second })
                 .All(pair => pair.first.CardRank == pair.second.CardRank - 1);


 (idx < cards.Count() - 1 &&
 (int)cards[idx + 1].CardRank == (int)x.CardRank + 1))).ToList();

He is pairing the four with the five.


On your call to cards.Sort, you are performing the sort, but not setting the new list back to the cards pointer.

Try doing a cards = cards.Sort (on the second line of your code).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜