Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
775 views
in Technique[技术] by (71.8m points)

c# - get items from 2 lists based on specific items values

I have 2 lists of myType and let's myType has properties x y and z;

class myType 
{
  public int x {get;set;}
  public int y {get;set;}
  public int? z {get;set;}
} 

List<myType> list1 = new List<myType>();
List<myType> list2 = new List<myType>();

what I want to do is to get list with matched items between the 2 lists where list1[i].x == list2[i].x && list1[i].y == list2[i].y regardless the value of z

here's my code

     List<MiHHUserComponent> components ;
     List<MiHHUserComponent> dbComponents;

i need the items matched between 2 lists where components[i].HHComponentFormName == dbComponents[i].HHComponentFormName && components[i].HHComponentName== dbComponents[i].HHComponentName

i tried the code below

 for (int j = 0; j < hhUsersIDs.Count; j++)
     {
        var hhUser = hhUsersIDs[j]; 

        var results = (from l1 in dbComponents
                       join l2 in components
                       on new { l1.HHUserID, l1.HHComponentFormName,l1.HHComponentName } 
                       equals new {hhUser.HHUserID  ,l2.HHComponentFormName,l2.HHComponentName }
                       select new
                       {
                          // select whatever you want here, eg:
                          HHUserID = hhUser.HHUserID,
                          HHComponentFormName = l1.HHComponentFormName,
                          HHComponentName = l1.HHComponentName
                       }).ToList(); 
     }

i have 2 lists with different counts of elements
and they have matched items
I need new list contains the matched items between them based on specific items in the the both lists
there's gonna be duplicate elements in the new list because the value of z will be taken from different value in another list i hope that's clear now

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can achieve this with simple linq extension methods.

var rresult = list1.Where(x=>  list2.Any(l=>l.x ==x.x && l.y ==x.y));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...