Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two list elements with LINQ

Tags:

c#

.net

linq

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?

like image 410
Gpx Avatar asked Jun 23 '10 14:06

Gpx


People also ask

How to compare elements of 2 lists in c#?

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);

What is Linq in C# with example?

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.


3 Answers

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)
like image 70
Daniel Brückner Avatar answered Sep 26 '22 14:09

Daniel Brückner


int i = 0;
_int.Where(x => 
{
    i++;
    return i < _int.Length && x == _int[i];
});
like image 27
Joel Coehoorn Avatar answered Sep 25 '22 14:09

Joel Coehoorn


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);
like image 32
Bill Barry Avatar answered Sep 22 '22 14:09

Bill Barry