简体   繁体   中英

Get a specific column value from a table when query through linq

var Sent =  request.Transactions.First(x => x.isSent == "4");
  1. When the above query runs it gets the complete list of a table row when condition meets. I just want a specific column value Date_Sent .
  2. Can I also create a if statement to check if the Date_Sent is null or not?

The First returns an item of the collection's type. Simple access it's property.

var sent = request.Transactions.FirstOrDefault(x => x.isSent=="4")?.Data_Sent;

If(sent == null) { }

See 2 things:

  • I suggest you use FirstOrDefault instead. It will not throw an exception if no item in sequence match predicate.

  • Use the ?. to access the property. It is called Null Propagation

If you do want to use the .Select then thr nicer way without creating temporary anonymous objects or breaking it into separate commands is to use the query syntax instead like this:

var sent = (from item in request.Transactions
            where item.isSent =="4"
            select Sent_Data).FirstOrDefault()

By the way I'd recommend looking into naming conventions in C#

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