我正在尝试使用 Linq lambda 做我认为非常简单的想法,它可能是,但我在任何教程中都找不到示例。
我有一个具有一些属性的简单类。我想根据该类中另一个值的值获取其中一个属性的列表。
下面是代码示例,使用 Linq 得到正确的结果:
public class Client
{
public int ClientId { get; set; }
public int ClientWorth { get; set; }
public strin ClientName { get; set; }
}
.
.
.
.
List<Client> allClients = this.GetAllClients();
List<string> richClients = (
from c in allClients
where c.ClientWorth > 500
select c.ClientId.ToString()).ToList();
谁能告诉我如何使用 lambda 来做到这一点 我可以执行以下操作:
List<Clients> richClients = allClients.Where(x => x.ClientWorth >500)
这给了我所有客户的列表,但我想得到一个只包含客户 ID 的字符串列表。
最佳答案
按客户值(value)过滤后,您应该投影结果 - 即仅选择客户 ID 值:
allClients.Where(c => c.ClientWorth > 500).Select(c => c.ClientId.ToString()).ToList()
进一步阅读:Enumerable.Select
关于c# - 如何编写 lambda 以根据对象中的另一个属性获取一个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43658973/