user1740381
user1740381

Reputation: 2199

How to intersect list in c#?

I have following list of Item objects in c#:

public class Item
{
    public int Id { get; set; }
    public List<string> Orders { get; set; }
}

List<Item> item = new List<Item>() { 
               new Item() { Id = 1, Code = 23, Orders = new List<string>() { "A", "B" }},
               new Item() { Id = 2, Code = 24, Orders = new List<string>() { "C", "D" }},
               new Item() { Id = 1, Code = 23, Orders = new List<string>() { "E", "F" }},
               new Item() { Id = 3, Code = 25, Orders = new List<string>() { "G", "H" }}
              };

I want to concat the Orders whose Id is same, so the output of above list should be:

    { 
      new Item() { Id = 1, Code = 23, Orders = new List<string>() { 'A', 'B', 'E', 'F' },
      new Item() { Id = 2, Code = 24, Orders = new List<string>() { 'C', 'D' },
      new Item() { Id = 3, Code = 25, Orders = new List<string>() { 'G', 'H' }
    };

How can i do this efficiently in c# ( using linq if possible ) ?

Upvotes: 1

Views: 233

Answers (3)

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

You can group your items by their id, then create new item for each id concatenate the orders:

item.GroupBy(x => x.Id)
    .Select(x => new Item
                 { 
                      Id = x.Key,     
                      Orders = x.SelectMany(a => a.Orders).ToList()
                  }).ToList();

Upvotes: 2

Servy
Servy

Reputation: 203821

You want to group the items based on their ID, and then create a new sequences based on all of the Orders for that group.

var query = items.GroupBy(item => item.Id)
    .Select(group => new Item
    {
        Id = group.Key,
        Orders = group.SelectMany(item => item.Orders).ToList()
    });

Note that this is not the intersection of any data. You're getting the union of all data within each group.

Upvotes: 7

p.s.w.g
p.s.w.g

Reputation: 149010

It appears what you want is something like this:

var output = items.GroupBy(i => i.Id)
                  .Select(g => new Item() 
                          {
                              Id = g.Key
                              Orders = g.SelectMany(i => i.Orders)
                                        .ToList()
                          });

Or in query syntax:

var output = 
    from i in items
    group i by i.Id into g
    select new Item() 
           {
               Id = g.Key
               Orders = g.SelectMany(i => i.Orders).ToList()
           };

Upvotes: 2

Related Questions