3

I've LINQ requests that return anonymous types like:

var result = context.Table1.Select(
    x => new
    {
        col1 = x.col1,
        col2 = x.col2
    }).ToList();

That works fine, until I want to hand over the result to another function.

Than I need to specify exactly, what's type the list is. I cannot use var anymore.

But if I use

List< (string col1, string col2)> result ...

I get an "Cannot implicitly convert type ..." error.

Yes, I can create a new class for each entity. But is this the only way to handle it?

3
  • Using dynamic can help you. Commented Nov 16, 2020 at 13:43
  • 1
    Does this answer your question? How to specify anonymous object as generic parameter? Commented Nov 16, 2020 at 14:04
  • I'm not sure whether the burden of typing a new class is a good reason not to do this. The reason for creating a special class in which you put your fetched data, is to do some information hiding. You want to hide how you get your data, you want to have the freedom to change this in the future without having to change the callers. For instance, if you add a Col3 to your returned class, your called won't have to change. Apparently he didn't need a Col3. They will have to change, if you return an anonymous tuple, even if they don't use Col3. Commented Nov 16, 2020 at 14:34

1 Answer 1

5

If you want to use a tuple type (that's what your (string col1, string col2) is) instead of an anonymous type (that's what your new { col1=x.col1...} is), you need another syntax:

List<(string col1, string col2)> list = context.Table1
    .Select( // linq to entities
    x => new
    {
        col1 = x.col1,
        col2 = x.col2
    })
    .ToArray() // go on with linq to objects for use of tuple types
    .Select(x => (col1: x.col1, col2: x.col2))
    .ToList();

ValueTuples aren't supported in Expression trees, so you might need to use a combination of anonymous types and tuple types in your query

See Tuple types, Choosing between anonymous and tuple types

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. That works for me :-) But why should I use "ToArray()" and not "AsEnumerable()" ?
I just wanted to show that you need to use linq to objects. AsEnumerable() might work as well, give it a try ;)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.