C# 在DataTable中使用distinct。选择函数
我有一个数据表,我想用这个数据表填充两个额外的数据表,这是我的表的一个简单形式C# 在DataTable中使用distinct。选择函数,c#,datatable,C#,Datatable,我有一个数据表,我想用这个数据表填充两个额外的数据表,这是我的表的一个简单形式 My data table columns are [name][family][id][propertyid][propertyEnergy] John smith 1 12 Gas John smith 1 13 Gas John smith 1 14 null John smith 1 15 Gas Hannah smith 2 16 Gas Hannah smith 2 17 Gas Hannah smit
My data table columns are
[name][family][id][propertyid][propertyEnergy]
John smith 1 12 Gas
John smith 1 13 Gas
John smith 1 14 null
John smith 1 15 Gas
Hannah smith 2 16 Gas
Hannah smith 2 17 Gas
Hannah smith 2 18 Gas
我想在datatable中使用此查询,从表中选择distinct[name][family][id]
结果是什么
John smith 1
Hannah smith 2
1 12 Gas
1 13 Gas
1 14 null
1 15 Gas
2 16 Gas
2 17 Gas
2 18 Gas
我再次在另一个数据表中使用此查询,从表中选择[id][propertyid][propertyEnergy],结果如下
John smith 1
Hannah smith 2
1 12 Gas
1 13 Gas
1 14 null
1 15 Gas
2 16 Gas
2 17 Gas
2 18 Gas
我搜索并发现我可以数据表。选择,但我看到的示例表明,我只能将Where sentense添加到数据表。选择,我不知道如何在其中执行Distinct
之类的操作,
你能帮我一下或给我一些提示吗?
非常感谢我将使用Linq To DataTable
来代替:
var distinctNames = table.AsEnumerable()
.Select(row => new
{
Name = row.Field<string>("Name"),
Family = row.Field<string>("Family"),
ID = row.Field<int>("ID")
})
.Distinct();
var distinctProperties = table.AsEnumerable()
.Select(row => new
{
ID = row.Field<int>("ID"),
PropertyID = row.Field<int>("PropertyID"),
PropertyEnergy = row.Field<int>("PropertyEnergy")
})
.Distinct();
有用的链接是否也需要Distinct
中的equalitycomparer
来忽略倍数?@HimBromBeere:不,因为匿名类型已经内置了它。匿名类型上的Equals
和GetHashCode
方法是根据属性的Equals
和GetHashCode
方法定义的,同一匿名类型的两个实例只有在其所有属性相等时才相等。请注意顺序很重要。@TimSchmelter感谢您的大力帮助..表是我的datatable吗?我用过它,但它说不包含它的定义..我应该在代码中写什么来代替var?@MajidHojati:是的,table是您的表:)@TimSchmelter所以我为什么得到这个错误错误20'System.Data.EnumerablerRowCollection'不包含'Distinct'的定义,并且找不到接受'System.Data.EnumerablerRowCollection'类型的第一个参数的扩展方法'Distinct'(您是否缺少using指令或程序集引用?)