I am having trouble comparing two lists using Linq.
My first list contains object instances, which contain a property of interest, to be compared against a second list that contains only values.
Say we have:
List<uint> referenceValues = new List<uint>(){1, 2, 3};
and
List<SomeObject> myObject= new List<SomeObject>();
Now the SomeObject() class has the property "Value" of type uint.
Note that "myObject" list may contains more elements than the "referenceValues" list and we therefore have to select the appropriate portion of "myObject" to be compared against "referenceValues".
I have found the following stack overflow question, which is related, but not quite what I am after: link
Here is what I have tried so far, but without success:
if (myObject
.GetRange((int)offset, count) // Extracted the object of interest from the list
.Where(x => referenceValues.Equals(x.Value)).Count() == 0) // Comparing the "Value" properties against the "referenceValues"
{
// Do something
}
I think I need to use "SequenceEqual" somehow, but I am not really getting how to.
Any advice would be very welcome.
EDIT
Reproducible example:
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
int offset = 0;
List<uint> referenceValues = new List<uint>(){1, 2, 3};
List<SomeObject> myObject= new List<SomeObject>(){new SomeObject(){Value=1},
new SomeObject(){Value=2},
new SomeObject(){Value=3}};
if (myObject
.GetRange(offset, referenceValues.Count()-1) // Extracted the object of interest from the list
.Where(x => referenceValues.Equals(x.Value)).Count() == referenceValues.Count()) // Comparing the "Value" properties against the "referenceValues"
{
// Do something
Console.WriteLine("Lists are matching!");
}
else
{
Console.WriteLine("Lists are not matching!");
}
}
}
public class SomeObject
{
public uint Value = 0;
}
EDIT2
Working solution as per suggestion from Guru Stron:
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
int offset = 0;
List<uint> referenceValues = new List<uint>(){1, 2, 3};
List<SomeObject> myObject= new List<SomeObject>(){new SomeObject(){Value=1},
new SomeObject(){Value=2},
new SomeObject(){Value=3}};
if (myObject.
GetRange((int)offset, referenceValues.Count())
.Select(someObject => someObject.Value)
.SequenceEqual(referenceValues))
{
// Do something
Console.WriteLine("Lists are matching!");
}
else
{
Console.WriteLine("Lists are not matching!");
}
}
}
public class SomeObject
{
public uint Value = 0;
}
Recommended book about Linq expressions: LINQ Pocket Reference