Home > Back-end >  How to make one collection using three collections?
How to make one collection using three collections?

Time:02-18

I want to make one collection of three according to certain conditions (with LINQ). let's say I have a Class:

class Collection
{
  public int id;
  public string name;
  public double weight;
}

Then I'm creating collections:

List<Collection> collection1 = new()
{
  new Collection() { id = 11, name = "Abraham 1", weight = 1.1 },
  new Collection() { id = 12, name = "Abraham 2", weight = 1.2 },
  new Collection() { id = 13, name = "Abraham 3", weight = 1.3 },
};

List<Collection> collection2 = new()
{
  new Collection() { id = 21, name = "Bill 1", weight = 2.1 },
  new Collection() { id = 22, name = "Bill 2", weight = 2.2 },
  new Collection() { id = 23, name = "Bill 3", weight = 2.3 },
};

List<Collection> collection3 = new()
{
  new Collection() { id = 31, name = "David 1", weight = 3.1 },
  new Collection() { id = 32, name = "David 2", weight = 3.2 },
  new Collection() { id = 33, name = "David 3", weight = 3.3 },
};

TODO 1. Condition: get 1st column from 1st collection, 2nd column from 2nd collection, 3rd column from 3rd column. result should be:

{
  new Collection() { id = 11, name = "Bill 1", weight = 3.1 },
  new Collection() { id = 12, name = "Bill 2", weight = 3.2 },
  new Collection() { id = 13, name = "Bill 3", weight = 3.1 }
}

TODO 2. Second case condition: get first elements from columns of all collections. result should be:

{
  new Collection() { id = 11, name = "Abraham 1", weight = 1.1 },
  new Collection() { id = 21, name = "Bill 1", weight = 2.1 },
  new Collection() { id = 31, name = "David 1", weight = 3.1 }
}

Please help.

CodePudding user response:

I'm not sure what you want to do but to get the result use below code:

//TODO 1
var result1 = collection1.Where( x => new int[] { 11, 12, 13 }.ToList().Contains(x.id)).OrderBy( x => x.id).ToList();

//TODO 2
var result2 = collection1.Concat(collection2).Concat(collection3)
            .Where( x => new int[] { 11, 21, 31 }.ToList().Contains(x.id)).ToList().OrderBy(x => x.id).ToList();

CodePudding user response:

If you want to merge multiple collections into one collection using LINQ then do this:

List<Collection> result = collection1.Concat(collection2).OrderBy(x => x.id).ToList();
  • Related