linq item get without foreach in selected new keyword

This question already has an answer here:

  • Linq code to select one item 8 answers

i wants to get a data using linq to SQL. I used for each like this is there is another way to get query data without for each .basically i wants to get d.name from query without using for each loop because i know there is one object no need to used loop for it.

var query=from d in db.table where d.id=2 select new {d.name}; foreach (var item in query) { string a=item.name; }

-------------Problems Reply------------

Looks like you want only the first name, you don't need an anoymous type here, you can just use FirstOrDefault like this:

db.table.Where(d => d.id == 2).Select(d => d.name).FirstOrDefault();

This will return the name of the first record with id 2 or return null if there is no such record.

If you want all names use ToList instead of FirstOrDefault

You can use FirstOrDefault with your code like this (if d.name is a string):

var query=(from d in db.table
where d.id==2
select d.name)
.FirstOrDefault();

Category:c# Views:2 Time:2017-09-10
Tags: linq

Related post

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.193 (s). 10 q(s)