Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
780 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...