Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ read Select values

Tags:

linq

c#-4.0

I have a LINQ query where I want to select and read the p.Api value.

 var api = DataAccessNew.Instance.dcServers.Where(p => p.Ip == IpAddress).Select(p => p.Api);

How do I read the p.Api value?

I have tried api.ToString() but I get SQL instead of actual column value.

like image 580
Tomas Avatar asked Sep 07 '25 03:09

Tomas


2 Answers

You are getting an IEnumerable<> back (and your ToString call is showing you the value of that expression).

If you are expecting a single value, do this:

var api = DataAccessNew.Instance.dcServers
    .Where(p => p.Ip == IpAddress)
    .Select(p => p.Api)
    .Single();

You might be interested to read about the other methods like Single(): SingleOrDefault, First, FirstOrDefault. Which one you used depends on whether you are expecting a single or multiple values returned (Single vs. First) and what you want to happen if there are no values (the *Default methods will return the type default instead of throwing an exception).

Or if you want to look at all the returned values:

var api = DataAccessNew.Instance.dcServers
    .Where(p => p.Ip == IpAddress)
    .Select(p => p.Api);

foreach (var apiValue in api)
{
    // apiValue  will have the value you're looking for.
}
like image 173
JohnD Avatar answered Sep 10 '25 18:09

JohnD


Try this snippet of code:

string apiValue = api.FirstOrDefault().ToString();
like image 43
Mahmoud Gamal Avatar answered Sep 10 '25 19:09

Mahmoud Gamal