IEnumerable <string>给出带有值[&#34; 1&#34;,&#34; 1&#34;]的结果,它应该给[&#34; 1&#34;,&#34; 2&#34;]

时间:2017-04-27 10:23:20

标签: c#

我有两个相互关联的课程,

 public class Class1
{
    public List<Class2> ClassTwo { get; set; }
}
public class Class2
{
    public string Name { get; set; }
    public List<Class3> ClassThree { get; set; }
}
public class Class3
{
    public string Name { get; set; }
    public string Data { get; set; }
}

然后我们有以下类的数据,如下,

Class1 collectionRequest = new Class1()
        {
            ClassTwo = new List<Class2>
        {
            new Class2 { Name = "1", ClassThree = new List<Class3> { new Class3 { Name = "A", Data = "X" } } },
            new Class2 { Name = "2", ClassThree = new List<Class3> { new Class3 { Name = "A", Data = "X" } } },
            new Class2 { Name = "3", ClassThree = new List<Class3> { new Class3 { Name = "B", Data = "Y" } } }
        }
        };

现在,我在LINQ下运行,

var config = collectionRequest.ClassTwo
  .SelectMany(cp => cp.ClassThree)
  .GroupBy(cfg => cfg.Name)
  .ToDictionary(g => g.Key, 
                g => g
                  .ToLookup(cfg => cfg.Data, 
                            cfg => collectionRequest.ClassTwo
                              .FirstOrDefault().Name));

当我在下面执行时,它会给我IEnumerable值[&#34; 1&#34;,&#34; 1&#34;],但我想返回IEnumerable值[&& #34; 1&#34;&#34; 2&#34;。]

LINQ需要进行哪些更改?

var data = config["A"]["X"]; // gives IEnumerable<string> with values ["1","1"]

1 个答案:

答案 0 :(得分:1)

问题在于您的价值&#39;查找的定义如下:

cfg => collectionRequest.ClassTwo.FirstOrDefault().Name

这会忽略该参数,并始终返回第一个Class2实例的名称 - 即1

下一个问题是,您没有引用Class2来自的实际Class3实例。你需要保持这一点。您可以使用LINQ查询语法执行此操作:

var c2c3ByC3Name =
    from c2 in collectionRequest.ClassTwo
    from c3 in c2.ClassThree
    group new {c2, c3} by c3.Name;

当然,你可以在方法语法中做同样的事情:

var c2c3ByC3Name = collectionRequest.ClassTwo
    .SelectMany(x => x.ClassThree, (c2, c3) => new {c2, c3})
    .GroupBy(x => x.c3.Name);

然后,您可以像以前一样创建查找:

var config = c2c3ByC3Name
    .ToDictionary(
        grp => grp.Key,
        grp => grp.ToLookup(x => x.c3.Data, x => x.c2.Name));

有关正常工作的演示,请参阅this fiddle