如何使用LINQ返回多个自选字段
以下是一个自己查询的LINQ返回多个自选字段的方法
首先,定义一个所需字段的类class,然后在LINQ 语句中使用select new 子句,由于要使用排重,所以为disctinct添加了IEqualityComparer,具体代码如下:
public partial class NewCars_Pedia : PageBase
{
public class PediaCategory
{
public string ColumnClass { get; set; }
public string CategoryChn { get; set; }
}
public class PediaComparer : IEqualityComparer<PediaCategory>
{
public bool Equals(PediaCategory source, PediaCategory dest)
{
return source.ColumnClass == dest.ColumnClass;
}
public int GetHashCode(PediaCategory obj)
{
return obj.ColumnClass.GetHashCode();
}
}
void OnInit()
{
DataTable dt = ParaCustom.GetAllPideaItems();
var lc = (from p in dt.AsEnumerable() select new PediaCategory { ColumnClass = p.Field<string>("columnClass"), CategoryChn = p.Field<string>("CategoryChn") }).Distinct(new PediaComparer());
rptFather.DataSource = lc.ToList();
rptFather.DataBind();
}
...
}