1

我有一个实体如下

public class A
    {
        public string TestMethodName { get; set; }
        public string FailedFor { get; set; }
    }

我正在填充,然后执行联合

            List<A> aCollection = new List<A>();
            List<A> bCollection = new List<A>();

            aCollection.Add(new A { TestMethodName = "Method1", FailedFor = "DPLServerURL" });
            aCollection.Add(new A { TestMethodName = "Method2", FailedFor = "DPLServerURL" });
            aCollection.Add(new A { TestMethodName = "Method3", FailedFor = "DPLServerURL" });
            aCollection.Add(new A { TestMethodName = "Method4", FailedFor = "DPLServerURL" });


            bCollection.Add(new A { TestMethodName = "Method1", FailedFor = "OrderXmlLocation" });
            bCollection.Add(new A { TestMethodName = "Method2", FailedFor = "OrderXmlLocation" });
            bCollection.Add(new A { TestMethodName = "Method5", FailedFor = "OrderXmlLocation" });

            var kk = aCollection.Union(bCollection);

我正在寻找的是 TestMethodNames 和 FailedFor 上的 group by 应该用逗号分隔。

例如最终输出应该是

Method1  DPLServerUrl,OrderXmlLocation
Method2   DPLServerUrl,OrderXmlLocation
Method3   DPLServerUrl
Method4   DPLServerUrl
Method5   OrderXmlLocation

我的尝试

 var mm  = kk.GroupBy(g => g.TestMethodName)
                  .Select(group =>
                        new
                        {
                            Name = group.Key,
                            AggregateFailedFor= group.Aggregate("",(a, b) => a.Join(",",b.FailedFor))
                        });

我收到编译时错误

成员 'string.Join(string, params string[])' 不能通过实例引用访问;改为使用类型名称来限定它

请帮忙

谢谢

4

1 回答 1

2

该错误是不言自明的。Join是静态的..所以你不能在实例变量上调用它。您必须通过类型名称(例如string)调用它:

Students = group.Aggregate("", (a, b) => string.Join(",", a, b.FailedFor))
//                                       ^^^^^^ this

请注意,聚合无疑会在结果的开头放置一个逗号,因为第一次调用将是“join nothing and FailedFor using a comma”,结果是“,FailedFor”。

编辑:

刚刚将您的代码更改为:

kk.GroupBy(g => g.TestMethodName)
    Select(group =>
        new
        {
            Name = group.Key,
            Students = group.Aggregate("", (a, b) => 
            {
                if (string.IsNullOrEmpty(a))
                {
                    return b.FailedFor;
                }
                else 
                {
                    return string.Join(",", a, b.FailedFor);
                }
            })
        });

..这就是结果(你说你在追求):

查询结果

于 2013-03-04T02:45:38.253 回答