简体   繁体   English

通过linq查询时从表中获取特定的列值

[英]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 . 我只想要特定的列值Date_Sent
  2. Can I also create a if statement to check if the Date_Sent is null or not? 我还可以创建一个if语句来检查Date_Sent是否为null吗?

The First returns an item of the collection's type. First返回集合类型的项目。 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. 我建议您改用FirstOrDefault 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: 如果确实要使用.Select then更好的方法而不创建临时匿名对象或将其分解为单独的命令,则可以使用查询语法,如下所示:

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# 顺便说一句,我建议您研究一下C#中的命名约定

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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