c# - Sort list by eventually existing value -


i have sort given list value may or may not given inside list of each element. if no value given, element should appear @ bottom of sorted list.

here's short example: want sort list items based on value of property has name foo

public class item {     public string name { get; set; }     public list<property> properties { get; set; } }  public class property {     public string name { get; set; }     public int value { get; set; } }  list<item> items = new list<item>() {     new item() {         name = "item 1",         properties = new list<property>() {             new property {                 name = "foo",                 value = 5             },             new property {                 name = "bar",                 value = 7             }         }     },     new item() {         name = "item 2",         properties = new list<property>() {             new property {                 name = "bar",                 value = 2             }         }     },     new item() {         name = "item 3",         properties = new list<property>() {             new property {                 name = "foo",                 value = 1             }         }     } 

the sorted list should contain items in order item 1, item 3, item 2

i tried this:

items.fetchorderby (     x => x.properties     .firstordefault     (         y => y.name = "foo"     )     .value ) .tolist(); 

...but got following exception: antlr.runtime.noviablealtexception

the problem when there's no property match, firstordefault returns null. around using null-coalescing operator:

items.fetchorderby (     x => (x.properties     .firstordefault     (         y => y.name == "foo"     )     // send non-matches bottom     ?? new property { value = int32.maxvalue })     .value ) .tolist(); 

Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -