Search code examples
c#.netlinqicomparer

LINQ custom sort using comparer


I have a class:

public class Item
{
  public int ownerID;
  public decimal value;
}

And an array of objects

Item[] items;

That looks like:

ownerID     value
476478      0.65
636566      0.2

And I have a second class

public class Owner
{
  public int ownerID;
  public int index;
}

And an array of objects

Owner[] owners;

The "owners" is sorted in specific order according the index and looks like:

ownerID    index
636566     1
476478     2

How can I sort the "items" in the same order as the "owners" using LINQ and comparer?

Would expect something like:

items = items.OrderBy(o => o.OwnerID, comparer(o))

where comparing made by "index".

Thanks a lot.


Solution

  • Assuming what you're trying to do is to order the items using the index property from the Owner object, something like this should do the job:

    var joined = items.Join(owners, item => i.OwnerId, owner => o.OwnerId, (item, owner) => new
    {
        Item = item,
        Index = owner.Index
    });
    
    var orderedItems = joined.OrderBy(j => j.Index).Select(j => j.Item);