简体   繁体   English

LINQ按子值排序

[英]LINQ ordering by a child value

I have an EF model that looks like: 我有一个EF模型,看起来像:

public class MetaData
{
    public ICollection<MetaDataDictionary> MetaDataDictionary { get; set; }
}

public partial class MetaDataDictionary
{
    public string Key { get; set; }
    public string Value { get; set; }
}

public List<MetaData> MetaDataList { get; set; }

...so I could have an instance like: ...所以我可以有一个像这样的实例:

MetaDataList 
  MetaData1
    MetaDataDictionary          
      { key = "aaa", value = "4" }
      { key = "bbb", value = "5" }     
      { key = "ccc", value = "6" }     
  MetaData2
    MetaDataDictionary 
      { key = "aaa", value = "1" }
      { key = "bbb", value = "2" }     
      { key = "ccc", value = "3" }              

The goal is to sort MetaDataList based on a value of a specific key (for example key "aaa") of the MetaDataDictionary, output should be: 目标是根据MetaDataDictionary的特定键(例如键“ aaa”)的值对MetaDataList进行排序,输出应为:

MetaDataList 
  MetaData1
    MetaDataDictionary          
      { key = "aaa", value = "1" }
      { key = "bbb", value = "2" }     
      { key = "ccc", value = "3" }     
  MetaData2
    MetaDataDictionary 
      { key = "aaa", value = "4" }
      { key = "bbb", value = "5" }     
      { key = "ccc", value = "6" }   

As you see, it is now sorted on values of key "bbb". 如您所见,它现在按键“ bbb”的值排序。

I tried: 我试过了:

var sorted = metaDataList.OrderBy(md => md.MetaDataDictionary.Select(mdd => mdd.Key == "aaa").Single()).ToList();

...but it complains about 'DbSortClause expressions must have a type that is order comparable'. ...但是它抱怨“ DbSortClause表达式必须具有可比的顺序类型”。

Any pointers how I can make this work? 有什么指针可以使我工作吗?

Thanks! 谢谢!

EDIT: just tried this: 编辑:刚刚尝试过:

var sorted = metaDataList.OrderBy(md => md.MetaDataDictionary.Where(mdd => mdd.Key == "aaa").Select(mdd => mdd.Value).FirstOrDefault()).ToList();

Seems to work, but if someone has a better solution, feel free to share :) 似乎可以工作,但是如果有人有更好的解决方案,请随时分享:)

Maybe this? 也许这个吗?

metaDataList.OrderBy(md => md.MetaDataDictionary.First(mdd => mdd.Key == "aaa").Value)
            .ToList();

I haven't tested it yet but believe it should work. 我尚未对其进行测试,但相信它应该可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM