John M
John M

Reputation: 14668

C# LINQ - Comparing a IEnumerable<string> against an anonmyous list?

The basic question

I have:

I want to query a list of objects that contain listA to see if they match to listB:

someObjectList.Where(x => x.listA == listB)

The comparison doesn't work - so how do I ensure that both lists are the same type for comparison?

The detailed question

I am grouping a larger list into a subset that contains a name and related date(s).

var listGroup = from n in list group n by new
   { n.NAME  } into d
   select new
   {
      NAME = d.Key.NAME, listOfDates = from x in d select new
                                     { Date = x.DATE } };

I have a object to hold the values for further processing:

class SomeObject
{
    public SomeObject()
    {
        _listOfDates = new List<DateTime>();
    }

    private IEnumerable<DateTime> _listOfDates;

    public IEnumerable<DateTime> ListOfDates
    {
        get { return _listOfDates; }
        set { _listOfDates = value; }
    }
 }

I am then iterating over the listGroup and adding into a generic List<> of SomeObject:

foreach(var item in listGroup)
{
    SomeObject so = new SomeObject();
    // ...do some stuff

    if (some match occurs then add into List<SomeObject>)

}

As I iterate through then I want to check the existing List<SomeOjbect> for matches:

var record = someObjectList.Where(x => x.NAME == item.NAME && 
                                       x.ListOfDates == item.listOfDates)
                           .SingleOrDefault();

The problem is that comparing x.ListOfDates against item.listOfDates doesn't work.

There is no compiler error but I suspect that the returned value lists are different. How to I get the lists to commonize so they can be compared?

Update #1

This seems to work to get the listOfDates into a similar format:

IEnumerable<DateTime> tempList = item.listOfDates.Select(x => x.DATE).ToList()

Then I followed the 'SequenceEqual' suggestion from @Matt Burland

Upvotes: 2

Views: 2852

Answers (1)

Matt Burland
Matt Burland

Reputation: 45155

You can just compare one IEnumerable<DateTime> to another IEnumerable<DateTime>, you need to compare the sequence. Luckily, there's Enumerable.SequenceEquals (in both static and extension method flavors) which should work here.

So something like:

var record = someObjectList
    .Where(x => x.NAME == item.NAME &&  x.ListOfDates.SequenceEquals(item.listOfDates))
    .SingleOrDefault();

Upvotes: 1

Related Questions