Return Multiple Columns in Linq to Sql?

2020-07-20 04:10发布

问题:

How do I return multiple columns with linq to sql in C#?

I tried to end my query with

select new { A.Product, A.Qty };

but this returns some anonymous type and I am not sure what the heck what to do with this, How to return it and how to extract information out of it. I want to put it in some sort of array.

thanks

回答1:

Are you trying to return the data from a method?

If so, you should just end the query with select A, which will produce the same type that A is.

If not, you can use the anonymous type the same way you use a regular type.

For example:

var results = from ... select new { A.Product, A.Qty };

foreach(var thing in results) {
    Console.WriteLine("{0}: {1}", thing.Product, Thing.Qty);
}

EDIT: To make it into a list, call ToList, like this:

var resultsList = results.ToList();


回答2:

Call tolist() on the query