lupus
lupus

Reputation: 53

C# orderby IQueryable by 2 different properties LinQ

I have an IQueryable of custom objects and want to implement sorting on them. Here is a simplified form of the objects I have in the database:

public class OrgObject : Entity
{
    public string sortStr { get; set; }
    public int sortVal  { get; set; }
    //... more different properties
    public virtual List<LinkedObject> links {get; set;}
}

public class LinkedObject : Entity  
{
    public string sortStr { get; set; }
    public int sortVal  { get; set; }
    //... more different properties
}

The problem is, some of the OrgObjects have no value for sortStr(or sortVal), then it should take the sortStr of LinkedObject. I tried implementing a separate getter to achieve that, but LINQ does not support that. I tried using:

 OrderBy(x => x.LinkedObject.sortStr).ThenBy(y => y.sortStr)

which doesn't work either. Is there a way to solve this with LINQ? Or any other clean and easy solution? Or do I need to implement my own? Thanks in advance

Upvotes: 1

Views: 351

Answers (2)

Scrobi
Scrobi

Reputation: 1200

Presuming you want the first or default option from the LinkedObject list then you can do something like this.

var ordering = o.OrderBy(x => x.sortStr ?? x.links.FirstOrDefault().sortStr);

Full example here:

var o = new List<OrgObject>()
{
    {
        new OrgObject()
        {
            sortStr = null,
            sortVal = null,
            links = new List<LinkedObject>()
            {
                new LinkedObject(){sortStr = "a", sortVal=1},
                new LinkedObject(){sortStr = "b", sortVal=2},
            }

        }
    },
    {
        new OrgObject()
        {
            sortStr = "c",
            sortVal = 3,
            links = new List<LinkedObject>()
            {
                new LinkedObject(){sortStr = "a", sortVal=1},
                new LinkedObject(){sortStr = "b", sortVal=2},
            }

        }
    },
    {
        new OrgObject()
        {
            sortStr = null,
            sortVal = null,
            links = new List<LinkedObject>()
            {
                new LinkedObject(){sortStr = "d", sortVal=1},
                new LinkedObject(){sortStr = "e", sortVal=2},
            }

        }
    },
 };

 var ordering = o.OrderBy(x => x.sortStr ?? x.links.FirstOrDefault().sortStr);

Upvotes: 1

Gerino
Gerino

Reputation: 1983

You could implement IComparable<OrgObject> in OrgObject that does your custom logic, whatever it might be, and just do .OrderBy(x=>x).

Upvotes: 0

Related Questions