我试图弄清楚我是否可以使用LINQ为我提供DataTable(FirstName,LastName,QTY)中的一些数据的不同值.我可以得到不同的值并填充我的列表,但我必须运行两个不同的LINQ查询来获取它....我相信有更好的方法来做到这一点:)
任何建议将不胜感激(LINQ非常新)
码:
public static List<StudentData> LinqDistinct(DataTable dt)
{
DataTable linqTable = dt;
//get the distinct values
var query =
(from names in dt.AsEnumerable()
select new {
FirstName = names.Field<string>("FirstName"),
LastName = names.Field<string>("LastName")
}).Distinct();
//fill my list with the distinct values
List<StudentData> sList = (from sa in query.AsEnumerable()
select new StudentData
{
FirstName = sa.FirstName,
LastName = sa.LastName
//Qty = names.Field<int>("Qty")
}).ToList();
return sList;}
Run Code Online (Sandbox Code Playgroud)
Shu*_*oUk 24
任何理由都不要简单地在不同之后进行投影,你可能需要在Distinct之后的AsEnumerable(),但这不是什么大不了的事.
public static List<StudentData> LinqDistinct(DataTable dt)
{
DataTable linqTable = dt;
return
(from names in dt.AsEnumerable()
select new {
FirstName = names.Field<string>("FirstName"),
LastName = names.Field<string>("LastName")
}).Distinct().Select(x =>
new StudentData() { FirstName=x.FirstName, LastName=x.LastName})
.ToList();
}
Run Code Online (Sandbox Code Playgroud)
从您的问题中不清楚数量是DataTable中的值,还是给定项目的重复数量,如Ecyrb的答案.但是,如果您的StudentData类实现IEquatable<StudentData>或覆盖Equals方法,这应该工作:
public static List<StudentData> LinqDistinct(DataTable dt)
{
return dt.AsEnumerable()
.Select(row => new StudentData
{
FirstName = row.Field<string>("FirstName"),
LastName = row.Field<string>("LastName"),
Qty = row.Field<int>("Qty")
})
.Distinct()
.ToList();
}
Run Code Online (Sandbox Code Playgroud)
如果StudentData不支持值比较,并且您无法将该支持添加到类中,则可能必须创建一个实现IEqualityComparer<StudentData>并将其传递给该Distinct方法.
| 归档时间: |
|
| 查看次数: |
75628 次 |
| 最近记录: |