简体   繁体   中英

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

The basic question:

I have:

  • IEnumerable listA.
  • var listB (this is an anonmyous list generated by a LINQ query)

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 through 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 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?

Update1

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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