展平linq查询的结果

时间:2015-03-26 05:47:15

标签: c# linq

我有这样的查询

var q = from a in audits
        join c in customers on a.CustomerID equals c.CustomerID
        select new { a, c };
return ControllerContext.Request.CreateResponse(HttpStatusCode.OK, 
    new { results = q.ToList() });

当我将结果发送到浏览器时,我收到了

results
0:
    a:
        field1: '',
        field2: ''
    c:
        column1: '',
        column2: ''
1: {}
....

如何更改c#以便结果如下

results
0:
    field1: '',
    field2: ''
    column1: '',
    column2: ''
1: {}
....

2 个答案:

答案 0 :(得分:1)

只需创建具有' a'属性的匿名类型和' c'应该做的伎俩。

var q = from a in audits
        join c in customers on a.CustomerID equals c.CustomerID
        select new { a.field1, a.field2, c.column1, c.column2 };

探索适用于基于Lambda的linq的SelectMany扩展方法。当使用基于lambda的linq时,它用于展平。

答案 1 :(得分:0)

根据这里的答案,您必须使用动态对象,该对象仅适用于C#4.0或更高版本:Is there an easy way to merge C# anonymous objects

首先,您创建一个函数:

static dynamic Combine(dynamic item1, dynamic item2)
{
 var dictionary1 = (IDictionary<string, object>)item1;
 var dictionary2 = (IDictionary<string, object>)item2;
 var result = new ExpandoObject();
 var d = result as IDictionary<string, object>; //work with the Expando as a Dictionary

 foreach (var pair in dictionary1.Concat(dictionary2))
 {
    d[pair.Key] = pair.Value;
 }

 return result;
}

然后在LINQ中调用它:

var q = from a in audits
    join c in customers on a.CustomerID equals c.CustomerID
    select Combine( a, c );