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: {}
....

2 Answers 2

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.

1
  • 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). Mar 26, 2015 at 6: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 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.