Compare two list elements with LINQ

后端 未结 5 1587
一生所求
一生所求 2021-01-13 07:42

I\'m trying to find a LINQ expression to compare two list elements.

What i want to do is:

List _int = new List { 1, 2, 3, 3, 4,         


        
5条回答
  •  旧时难觅i
    2021-01-13 08:14

    It's an interesting problem, I would perhaps go for query expression syntax where it can be done like this

    int[] array = {1,2,3,3,4,5};
    var query = from item in array.Select((val, index) => new { val, index })
                join nextItem in array.Select((val, index) => new { val, index })
                on item.index equals (nextItem.index + 1)
                where item.val == nextItem.val
                select item.val;
    

    Which would extract 3 from the array (or list). Of course, what can be done in query expression can obviously be done in lambda.

    Edit Joel's solution is much simpler than mine and if you just need it to work on a List or an array, it is perfect. If you need something more flexible to work against any IEnumerable, then you would aim for something like the above (or something obviously better).

提交回复
热议问题