Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 不同的方法重复数据_C#_Asp.net_Linq_Datatable_Distinct - Fatal编程技术网

C# 不同的方法重复数据

C# 不同的方法重复数据,c#,asp.net,linq,datatable,distinct,C#,Asp.net,Linq,Datatable,Distinct,使用以下命令时,我会得到重复的行: DataTable dt = list.AsEnumerable().Distinct().CopyToDataTable(); 为什么Distinct()不起作用 我的数据表结构: serial,doc_content,doc_name,selected int ,Byte[] ,string ,int 您正在对一系列数据行调用Distinct()。我不相信DataRow会覆盖Equals,因此任何两个DataRow对象都会比较为不

使用以下命令时,我会得到重复的行:

 DataTable dt = list.AsEnumerable().Distinct().CopyToDataTable();  
为什么
Distinct()
不起作用


我的数据表结构:

serial,doc_content,doc_name,selected
int   ,Byte[]     ,string  ,int

您正在对一系列数据行调用
Distinct()
。我不相信
DataRow
会覆盖
Equals
,因此任何两个
DataRow
对象都会比较为不相等

您需要将
IEqualityComparer
传递给
Distinct()
,或者首先投影到另一个类型(例如,一个匿名类型,它已经实现了相等比较)并对新序列调用
Distinct()

如果您想继续使用
DataRow
,实现相等比较器可能是最简单的方法。虽然看起来很有希望(我以前不知道),但由于
byte[]
字段的原因,它在您的特定情况下可能无法工作

就我个人而言,我喜欢尽可能快地将数据转换成更具体的类型,但是YMMV。请注意,如果将整个
数据表
投影到更具体的类型,则可以将
选择
部分改为
Where
子句:

var list = table.AsEnumerable()
     .Select(row => new { Serial = row.Field<string>("serial"),
                          ContentBase64 = Convert.ToBase64String(row.Field<byte>("doc_content")),
                          Name = row.Field<string>("doc_name"),
                          Selected = row.Field<int>("selected") })
     .Where(x => x.Selected == 1)
     .Distinct()
     .ToList();
var list=table.AsEnumerable()
.Select(row=>new{Serial=row.Field(“Serial”),
ContentBase64=Convert.tobase64字符串(行字段(“文档内容”),
名称=行字段(“文件名”),
Selected=row.Field(“Selected”)})
.其中(x=>x.所选==1)
.Distinct()
.ToList();

请注意,我正在将内容转换为base64字符串,以便进行相等比较。这不是最有效的方法,但很简单:)如果你不需要内容,您可以去掉该部分投影。

Distinct
将比较对象引用,因为
DataRow
不会覆盖
object
中的默认
Equals
GetHashCode
方法,以考虑行中存储的值

有一个重载允许您指定自己的相等比较器,还有一个类实现所需的
IEqualityComparer
接口

然后您可以这样使用它:

var distinct = list.AsEnumerable()
    .Distinct(DataRowComparer.Default)
    .CopyToDataTable();

什么是
列表
列表中有什么?尝试使用
list.Distinct().AsEnumerable().CopyToDataTable()
var list=dt_temp.Select(“selected=1”)
int,byte[],string,int
@只知道这个代码没有多大帮助。什么是
dt_temp
?那类型的顺序是什么?
serial,doc\u content,doc\u name,selected
你能给我一个例子,怎么做吗?有没有办法使用
CopyToDataTable()之后that@just_name:您必须转换回数据行-但您真的要这样做吗?就我个人而言,我宁愿尽快离开
DataTable
DataRow
,还有一件事,为什么你不使用
doc\u content=(row.Field(“doc\u content”)
而不是“将内容转换为base64字符串”@只要名称
byte[]
使用引用相等,
string
使用值相等。(默认情况下)Well
Distinct()
将调用
GetHashCode
Equals
。这里只比较“通过引用”,因为
DataRow
没有覆盖
Equals
。我不知道DataRowComparer。以前的默认值是-nice。但不确定它是否能与
字节[]
字段一起工作;这取决于内部存储的方式。