简体   繁体   中英

Find Matching Fields of List and IEnumerable objects in C#

There is a long and tedious way I could perform the task I want to accomplish, but I am thinking there must be a way using Linq or some other neater more efficient technique to achieve this. I have a IEnumberable lets call it people1 with properties firstName and lastName, I also have a List lets call it people2 also with firstName and lastName properties. I need to store only the people1 where the firstName and lastName values of people2 match that of people1.

This pseudo code doesn't work but it might explain better what I hope to achieve than that wordy explanation:

people3 = people1.Select(x => x.firstName IN (people2.firstName) && x.lastName IN (people2.lastName))

I am kinda new to this so the only way I came up with of doing it was looping through the people2 list elements comparing people1 and if it matches storing it in people3. This will work but I am assuming there is a nicer way to do it and I am trying to learn new things so I thought I would throw this out there to see what your great minds come up with. :)

UPDATE:

After playing around a bit I am close but can't seem to figure out how to add the matching items to a new IEnumerable object. Here is the code I have, it fails on the "Add" line:

IEnumerable<dynamic> people3 = null;

foreach(var person in people1)
{
   if(people2.Exists(x => x.FirstName == people1.FirstName))
   {
      people3.Add(person);
   }
}

NOTICE: This solution is only applicable for sequences of the same type.

Enumerable.Intersect<T>(IEnumerable<T>, IEnumerable<T>, IEqualityComparer<T>)


Basically, you want to use linq to find the matches between two sequences using a custom equality comparison, which in your case would compare true for the FirstName and LastName matching. Though, what would happen if two people shared the same exact name but they are different people? If that isn't an issue in your domain, then ignore that problem.

I am aware this probably isn't the most elegant solution, however this is the best way I was able to figure out how to accomplish my goal. Please if you have improvement by all mean I am open to making this piece of code a little nicer.

//populate IEnumerable<dynamic> people1
//populate List<dynamic> people2

List<dynamic> people3 = new List<dynamic>();

foreach (var person in people1)
   if(people2.Exists(x=>x.FirstName==person.FirstName)
      people3.Add(person);

people1 = people3;

I was hoping to avoid a for loop but I think the fact that I have 2 different sequence types has made it inevitable.

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