简体   繁体   English

使用LINQ比较两个列表元素

[英]Compare two list elements with LINQ

I'm trying to find a LINQ expression to compare two list elements. 我正在尝试找到一个LINQ表达式来比较两个列表元素。

What i want to do is: 我想做的是:

List<int> _int = new List<int> { 1, 2, 3, 3, 4, 5};
_int.Where(x => x == _int[(_int.IndexOf(x)) + 1]);

Unfortunately, only the last +1 jumps out of the list's range. 不幸的是,只有最后一个+1跳出了列表的范围。

How can I compare one item with its next in the list in a LINQ expression? 如何在LINQ表达式中将一个项目与列表中的下一个项目进行比较?

Not that nice but should work. 不是很好,但应该工作。

list.Where((index, item) => index < list.Count - 1 && list[index + 1] == item)

Or the following. 或者以下。

list.Take(list.Count - 1).Where((index, item) => list[index + 1] == item)
int i = 0;
_int.Where(x => 
{
    i++;
    return i < _int.Length && x == _int[i];
});
List<int> _int = new List<int> { 1, 2, 3, 3, 4, 5 };
Enumerable.Range(0, _int.Count - 1)
    .Select(i => new {val = _int[i], val2 = _int[i + 1]})
    .Where(check => check.val == check.val2)
    .Select(check => check.val);

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). 哪个会从数组(或列表)中提取3。 Of course, what can be done in query expression can obviously be done in lambda. 当然,在查询表达式中可以做的事情显然可以在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. 编辑 Joel的解决方案比我的解决方案简单得多,如果你只需要它来处理List或数组,它就是完美的。 If you need something more flexible to work against any IEnumerable, then you would aim for something like the above (or something obviously better). 如果你需要一些更灵活的东西来对抗任何IEnumerable,那么你就会瞄准上面的东西(或明显更好的东西)。

If you really want to do it with a lambda expression, add a bound check (that either always returns the last element or never, your choice). 如果你真的想用lambda表达式来做,那就添加一个绑定检查(要么总是返回最后一个元素,要么永远不返回你的选择)。

An iterative approach would be more readable though, IMO. IMO,迭代方法会更具可读性。

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

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