I'm trying to find a LINQ expression to compare two list elements.
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.
How can I compare one item with its next in the list in a LINQ expression?
By using Intersect , we can check which elements in source list are also contained in compare list. var source = new List<string>() { "a", "b", "c" }; var compare = new List<string>() { "b", "c", "d" }; var result = source. Intersect(compare);
LINQ (Language Integrated Query) is uniform query syntax in C# and VB.NET to retrieve data from different sources and formats. It is integrated in C# or VB, thereby eliminating the mismatch between programming languages and databases, as well as providing a single querying interface for different types of data sources.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With