Ralph Jason Caballes
Ralph Jason Caballes

Reputation: 151

Sort item based on another collection item

I want to sort an object and sort the object based on another collection item in LINQ. Say I have an object as follows:

 [0] = { ID: 1090 , Name : Test1 }
 [1] = { ID: 120 , Name : Test2 }
 [2] = { ID: 1240 , Name : Test3 }

To be sorted based on this item collection

 ColItem : [0] = 1240
 [1] = 120
 [2] = 1090

So expected output should be:

 [0] = { ID: 1240 , Name : Test3 }
 [1] = { ID: 120 , Name : Test2 }
 [2] = { ID: 1090 , Name : Test1 }

I know I can do this by doing a loop in the ColItem, then mapped the value in the ID field from the object. But I want to do it in LINQ with a single line of code. Is that possible? Then, how to do that in LINQ with a single query?

Upvotes: 1

Views: 65

Answers (1)

mohabbati
mohabbati

Reputation: 1158

The following code works for your purpose, but it's not something I like very much:

class Collection1
{
    public int ID { get; set; }

    public string Name { get; set; }
}

class Collection2
{
    public int ID { get; set; }
}

...

var result = collection1s
      .Join(collection2s.Select((x, i) => new { Index = i, x.ID }), 
          c1 => c1.ID, c2 => c2.ID, (c1, c2) => new { c2.Index, c1.ID, c1.Name })
      .OrderBy(x => x.Index)
      .Select(x => new Collection1() { ID = x.ID, Name = x.Name } )
      .ToList();

I used join two collections by ID, then used the second collection index to sort the result, and finally created a new object as the type of the first collection.

Upvotes: 1

Related Questions