根据对象列表中的属性排序地图

时间:2013-11-04 15:09:39

标签: c# linq

遇到LINQ atm的问题。 我目前有一个可以有两个名字的类 - MeterName和ChannelName;两个字符串。但是,ChannelName属性可能为空或null。 这个类叫做ChannelRecord,它包含一些与Meter + Channel名称相关的其他属性。

这些存储在List中,List映射到字典中的DateTime。这意味着我们有:

Dictionary<DateTime, List<ChannelRecord>> outputMap = ....;

我正在尝试根据他们的电表和电台对频道记录进行排序。频道名称,以米开始,首先是数字和符号,最后是z。

到目前为止,我的代码看起来像这样:

var orderedMap = outputMap.Select(x => x.Value) // as in KeyValuePair<TKey,TValue>
        .OrderBy(list => list.Select(record => record.MeterName))
        .ThenBy(list => list.Select(record => record.ChannelName));

但是,我得到的例外是“其中一个对象必须实现IComparable”。这很有趣,因为AFAIK,字符串实现IComparable。我知道KeyValuePair没有,但我.Select()来自它的值。

做什么?

2 个答案:

答案 0 :(得分:0)

问题是list => list.Select(record => record.MeterName)内的OrderBy会返回IEnumerable<string>,而不是IComparable

如果您想重新排序里面的字典,但保持字典本身不变(即日期键保持不变),您可以这样做:

var orderedMap = outputMap
    .ToDictionary(
        x => x.Key
    ,   x => x.Value
           .OrderBy(element => element.MeterName)
           .ThenBy(element => element.ChannelName)
           .ToList()
    );

答案 1 :(得分:0)

在这部分:

.OrderBy(list => list.Select(record => record.MeterName))

lambda的结果是IEnumerable字符串,而不是单个字符串。 IEnumerable可能只包含一个字符串,但现在编译器可以知道这一点。

试试这个:

var orderedMap = outputMap.Select(x => x.Value) // as in KeyValuePair<TKey,TValue>
    .OrderBy(list => list.Select(record => record.MeterName).First())
    .ThenBy(list => list.Select(record => record.ChannelName).First());