简体   繁体   中英

Checking if a list's item has a property contained in another list of items

I have two lists that have different types as their items. Both their types (Item1 and Item2) have a property called "Name". I want to iterate through all the items in list1. If any item in list1 has a name that is the same as an item's name in list2, then I want to add it to listWhereNamesMatch.

List<Item1> list1;
List<Item2> list2;
List<Item1> listWhereNamesMatch;

foreach (var item1 in list1)
{
     foreach (var item2 in list2)
     {
          if(item1.Name == item2.Name)
          {
               listWhereNamesMatch.add(item1);
               break;
          }
     }
 }

I do have a query, but I want to know if there's a cleaner or more efficient way to do this. Here's what I have:

var results = list1.FindAll(o => list2.FirstOrDefault(b => b.Name == o.Name) != null);
listWhereNamesMatch.AddRange(results);

You could try the following one:

var results = list1.Join(list2, x=> x.Name, y => y.Name, (x,y) => x);
listWhereNamesMatch.AddRange(results);

or in another form:

var results = from a in list1
              join b in list2
              on a.Name equals b.Name
              select a;

listWhereNamesMatch.AddRange(results);
var list1 = new List<MyItem>();
var list2 = new List<MyItem>();

var listWhereNamesMatch = list1.Intersect(list2);


// implement IEquatable within your class
class MyItem : IEquatable<MyItem>
{
    public string Name { get; set; }

    bool IEquatable<MyItem>.Equals(MyItem other)
    {
        return this.Name == other.Name;
    }
}

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