使用linq从List<Customer>获取List<int>

7

我有一个客户列表customer,想要将其id单独列为一个列表List<int>

我尝试使用以下方法:

customerList.Cast<int>.Distinct().ToList() 

但它没有起作用。我还想在列表中区分不同的客户。

我该如何使用 LINQ 语法实现这个功能?我应该在我的查询中进行哪些更改?


你能展示一些你尝试过的代码吗?至少客户类的属性会很好。 - wizzardz
尽管原帖可能需要更多的描述,但我并不认为这个问题含糊不清。我非常清楚他想要做什么。 - Louise Eggleton
2个回答

26

试一下这个:

List<int> customerIds = customerList.Select(c => c.Id).Distinct().ToList();
代码假设你的客户对象拥有一个返回整数的Id属性。

10
从您的客户列表中选择ID,然后使用ToList获取ID列表。
var IdList = customerList.Select(r=> r.ID).ToList();

尝试获取不同的Id:

var IdList = customerList.Select(r=> r.ID).Distinct().ToList();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接