动态GroupBy名称和值的属性列表

时间:2014-05-06 21:19:35

标签: c# .net linq group-by

我似乎无法想出这个。我已经在SO上找到了这个,LINQ: grouping based on property in sublist。但是,我必须通过运行时提供的多个Name-Value对对Document进行分组。这是我的类型:

public class Document
{
    public string Name { get; set; }
    public List<Metadata> Metadata { get; set; }
}

public class Metadata
{
    public string Name { get; set; }
    public string Value { get; set; }
}

现在,如果我有:

var groupableProperties = new List<string> { "Color", "Shape" };

var documents = new List<Document>()
{
    new Document()
    {
         Name = "sample.txt",
         Metadata = new List<Metadata>()
         {
             new Metadata() { Name = "Color", Value = "Red" },
             new Metadata() { Name = "Shape", Value = "Circle" },
             new Metadata() { Name = "Texture", Value = "Rough" }
         }
    },
    new Document()
    {
        Name = "sample2.txt",
        Metadata = new List<Metadata>()
        {
            new Metadata() { Name = "Color", Value = "Red" },
            new Metadata() { Name = "Shape", Value = "Circle" },
            new Metadata() { Name = "Texture", Value = "Smooth" }
        }
    },
    new Document()
    {
        Name = "sample3.txt",
        Metadata = new List<Metadata>()
        {
            new Metadata() { Name = "Color", Value = "Red" }
        }
    }
};

在运行时提供groupableProperties,我想最终得到2组 Documents ,Group 1:sample.txt,sample2.txt和Group 2:sample3.txt。

1 个答案:

答案 0 :(得分:0)

执行此操作的方法是

from d in documents
group d by string.Join("", d.Metadata
                            .Where(m => groupableProperties.Contains(m.Name))
                            .OrderBy (x => x.Name)
                            .Select(x => x.Value)
                      ) into g
select g;

这会创建两个组,其中包含键RedCircle(sample.txt,sample2.txt)和Red(sample3.txt)。

按名称排序可确保在找到groupableProperties中的名称时,键字符串始终相同。