0

I have a query like this

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() });

When I send the result of this to the browser I receive this

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

How do I change the c# so the result is like this

results
0:
    field1: '',
    field2: ''
    column1: '',
    column2: ''
1: {}
....
Rufus L
  • 36,127
  • 5
  • 30
  • 43
Paul
  • 1,457
  • 1
  • 19
  • 36

2 Answers2

1

Simply creating the anonymous type with the properties of 'a' and 'c' should do the trick.

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 };

Do explore the SelectMany extension method that works with Lambda based linq. It is use full for flattening when using lambda based linq.

Neeraj
  • 596
  • 7
  • 9
  • You could use reflection to generate an Expression Tree that could be passed to `Select` method, but because you'd also have to create a new type at runtime to hold the results, I don't think that will really work (that type wouldn't be usable, because you'd have to use reflection to get anything our of results anyway). – MarcinJuraszek Mar 26 '15 at 06:12
0

With the answer from here, you have to use the dynamic object, which is only avaiable for C#4.0 or later: Is there an easy way to merge C# anonymous objects

First, you create a function:

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;
}

And then just call it in the LINQ:

var q = from a in audits
    join c in customers on a.CustomerID equals c.CustomerID
    select Combine( a, c );
Community
  • 1
  • 1
Huy Hoang Pham
  • 4,107
  • 1
  • 16
  • 28