C# 用于获取值为“In”的单个列的数据的 Lambda 表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11277606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 17:14:38  来源:igfitidea点击:

Lambda expression to get data for a single column where values "In"

c#lambda

提问by user1204195

I have a SQL table "tablex" with 3 columns(A, B ,C ).

我有一个包含 3 列(A、B、C)的 SQL 表“tablex”。

The following lambada expression returns 10 rows.

以下 lambda 表达式返回 10 行。

var versions = versionRepository.GetVersions(a.id)

Column B of the 10 results store data as: 1,2,3,4,5,6,7,8,9,10

10个结果的B列存储数据为:1,2,3,4,5,6,7,8,9,10

Can someone help me with the lambda expression to only get results for column C where b in (2,3,4).

有人可以帮助我使用 lambda 表达式只获得 C 列的结果,其中 b 在 (2,3,4) 中。

So I should only get 3 rows of column C data.

所以我应该只得到 3 行 C 列数据。

采纳答案by Guffa

Use the Whereextension method to filter the data, and the Selectextension method to get only the Cproperty:

使用Where扩展方法过滤数据,使用Select扩展方法只获取C属性:

var versions =
  versionRepository.GetVersions(a.id)
  .Where(v => v.B >= 2 && v.B <= 4)
  .Select(v => v.C);

(The part v => v.Cis an example of a lambda expression.)

(该部分v => v.C是 lambda 表达式的示例。)

回答by JK.

You can use Containsto check if it matches one of the numbers you are looking for:

您可以使用Contains它来检查它是否与您要查找的数字之一匹配:

List<int> ids = new List<int> { 2, 3, 4, 10 };

var versions =
  versionRepository.GetVersions(a.id)
  .Where(v => ids.Contains(v.B))
  .Select(v => v.C);

The trick here is to reverse it around, instead of checking if B is one of the desired numbers, just check if the list of numbers contains B.

这里的技巧是反转它,而不是检查 B 是否是所需的数字之一,只需检查数字列表是否包含 B。