简体   繁体   中英

How get a specific value from a query in Linq

I am just starting learning about Linq. I wrote some examples but there is a doubt that I haven't been able to solve.

I am working with the Northwind database, I just used the tool called SqlMetal in order to make all the modeling.

Right now I just wrote the following query:

var q = from c in db.Customers
        from o in c.Orders
        where c.City == "London"
        select new { c, o };

I know that this query brings to me a resulting set of data that contains all the columns of the Customers and Orders tables for the given condition ( c.City == "London" ). But my question is:

After executing that query, How can I get the value of the column Customers.CustomerID and Orders.OrderID FROM THE VARIABLE q ?

Maybe this is a silly question but I have been struggling with this for a couple hours, thanks in advance.

var theSoleItem = q.First();
theSoleItem.CustomerID
theSoleItem.OrderID

Also, if that was the only columns you cared about, your initial query would be faster with:

select new {c.CustomerID, o.OrderID}

You could also change the names as you go:

select new {CustID = c.CustomerID, OrdID = o.OrderID}

The latter being the only option if rather than directly referencing a property, you reference a method call.

The variable q is now a sequence of anonymous objects that have two objects in it: Customer and Order. You can easy iterate over it:

foreach(var item in q)
{
    Console.WriteLine("CustomerID = " + item.CustomerID + " order ID = " + item.OrderID);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM