按最终现有值排序列表

时间:2013-08-15 22:58:07

标签: c# asp.net list sorting nhibernate

我必须通过一个值对给定列表进行排序,该值可能会也可能不会在每个元素的另一个列表中给出。如果没有给出值,则此元素应出现在已排序列表的底部。

以下是一个简短的示例:我想根据名称为Items

Value的{​​{1}}对列表Property进行排序
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 } } } ItemItem 1

的顺序包含Item 3 s

我试过了:

Item 2

...但得到以下异常:items.FetchOrderBy ( x => x.Properties .FirstOrDefault ( y => y.Name = "foo" ) .Value ) .ToList();

1 个答案:

答案 0 :(得分:1)

问题是当没有属性匹配时,FirstOrDefault返回null。您可以通过使用null-coalescing运算符来解决这个问题:

items.FetchOrderBy
(
    x => (x.Properties
    .FirstOrDefault
    (
        y => y.Name == "foo"
    )
    // Send non-matches to the bottom
    ?? new Property { Value = Int32.MaxValue })
    .Value
)
.ToList();
相关问题