Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a List<> to another List<> with Comparsion in c#

I an having Two Lists. I want to get the matched and unmatched values based on ID and add the results to another List. I can get both of these using Intersect/Except.

But I can get only ID in the resultant variables (matches and unmatches) . I need all the properties in the Template.

List<Template> listForTemplate = new List<Template>();
List<Template1> listForTemplate1 = new List<Template1>();

 var matches = listForTemplate .Select(f => f.ID)
                      .Intersect(listForTemplate1 .Select(b => b.ID));

 var ummatches = listForTemplate .Select(f => f.ID)
                     .Except(listForTemplate1.Select(b => b.ID));

     public class Template
     {
       public string ID{ get; set; }
       public string Name{ get; set; }
       public string Age{ get; set; }
       public string Place{ get; set; }
       public string City{ get; set; }
       public string State{ get; set; }
       public string Country{ get; set; }
     }
     public class Template1
     {
         public string ID{ get; set; }
     }
like image 238
Anees Deen Avatar asked May 11 '13 12:05

Anees Deen


People also ask

How do I pass a value from one list to another in C#?

To add the contents of one list to another list which already exists, you can use: targetList. AddRange(sourceList);

What is deep copy and shallow copy in C#?

A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements. Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection duplicated.

What is a copy constructor C#?

A constructor that creates an object by copying variables from another object or that copies the data of one object into another object is termed as the Copy Constructor. It is a parameterized constructor that contains a parameter of the same class type.


1 Answers

If you don't want to implement IEquality for this simple task, you can just modify your LINQ queries:

var matches = listForTemplate.Where(f => listForTemplate1.Any(b => b.ID == f.ID));

and

var unmatches = listForTemplate.Where(f => listForTemplate1.All(b => b.ID != f.ID));

You might want to check for null before accessing ID, but it should work.

like image 146
MAV Avatar answered Sep 26 '22 02:09

MAV