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
603 views
in Technique[技术] by (71.8m points)

c# - How to compare two lists and update a list value

Hi i am trying the below requirement.

class:

public class Items
    {
        public string ID { get; set; }
        public string NAME { get; set; }
        public string type { get; set; }


    }

list1:

        ID NAME type
        1  aaa  1a
        2  bbb  2b
        3  ccc  3b
    

list2:

        ID NAME 
        1a  aaa  
        2b  bbb  
        3c  ccc 
        4d  ddd
        5e  eee
        6f  fff

Compare the two lists list1 and list2.

i am trying the below query Compare the two lists list1 and list2.

List<Items> list3= list2.Where(x => list1.Any(z=>x.id==z.type)).ToList();

i am getting the below result for above query:

        ID NAME 
        1a  aaa  
        2b  bbb  
        3c  ccc 

expected result: i want the list1 ID, list2 Name where list1.type==list2.ID to form the list3 like below

list3:
    
        ID NAME 
        1  aaa  
        2  bbb  
        3  ccc 

Any Help or Suggestion to the above query. Thanks, Sudha.


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

1 Answer

0 votes
by (71.8m points)

Join two lists on values of id and type fields and then select desired result:

from l1 in list1
join l2 in list2 on l1.type equals l2.id
select new { l1.id, l1.name }

In the select operator you can select whole l1, or create non-anonymous type instance. Same in method syntax:

list1.Join(list2, l1 => l1.type, l2 => l2.id, (l1, l2) => new { l1.id, l1.name })

Note: use PascalCase naming for properties.


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

...