Constummer
Constummer

Reputation: 3

How to order a nested Linq object via orderBy

so I wanted to order a nested object, this "someObject" object has "Values" object as in its inside. How do I order this nested object via orderBy.

mySendendId=11

someObject=
Id=1
Values===
          Id=10     numeric =20     text=null
          Id=11     numeric =1.4    text=null
          Id=12     numeric =32     text=null
          Id=13     numeric=null    text=”abcde”

Id=2
Values===
          Id=10     numeric =21     text=null
          Id=11     numeric =1.2    text=null
          Id=12     numeric =33     text=null
          Id=13     numeric=null    text=”bcde”

Id=3
Values===
          Id=10     numeric =22     text=null
          Id=11     numeric =1.3    text=null
          Id=12     numeric =34     text=null
          Id=13     numeric=null    text=”cde”

someObject =1,2,3

orderedObject = someObject.orderBy(a=>a.Values.(b=>b.numeric).Where(b=>b.Id= =mySendendId))

orderedObject =2,3,1

I already tried

orderedObject= someObject.OrderBy(a => a.Id).Where(a => a.Values.OrderBy(b => b.Numeric).Any(b => b.Id == mySenedId));

but i just returned original object without ordered.

Upvotes: 0

Views: 661

Answers (1)

Christoph Sonntag
Christoph Sonntag

Reputation: 4629

If I understand you correctly, this should do what you are looking for:

orderedObject= someObject.OrderBy(a => a.Values.SingleOrDefault(b => b.Id == mySenedId)?.numeric ?? int.MaxValue);

As there is no sample to try it out I hope I theorycrafted it correctly.

It should follow this logic:

  • From each object a in someObject get the Values and find the value b with the matching Id
  • If there is more than one match, throw an exception (this is what the SingleOrDefault does compared to FirstOrDefault)
  • If there is no value matching the Id, SingleOrDefault will return null - thus the null coalesce will select int.MaxValue - this means values with no match - or numeric being null - will be sorted to the end
  • If there is a value matching the Id, select the numeric field from the matching child b.
  • Order by the selected values

Upvotes: 1

Related Questions