1

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?

  • Does this answer your question? [Sort a collection based on another collection](https://stackoverflow.com/questions/7750475/sort-a-collection-based-on-another-collection) – derpirscher Nov 29 '21 at 07:49
  • Sort list in C# with LINQ? https://stackoverflow.com/questions/4003835/sort-list-in-c-sharp-with-linq – senthilkumar2185 Nov 29 '21 at 07:53

1 Answers1

1

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.

mohabbati
  • 1,162
  • 1
  • 13
  • 31