LINQtoSQL错误:类型'System.String'不支持序列运算符

Spo*_*com 8 linq-to-sql

出于某种原因,我的代码将无效.

    from tan in TANS
    where tan.ID.ToString().Count() != 1
    select tan
Run Code Online (Sandbox Code Playgroud)

我想选择表中重复的所有ID,所以我使用count!= 1,我得到这个错误.

NotSupportedException:类型'System.String'不支持序列运算符

请帮忙?

Jam*_*ran 13

tan.ID.ToString() 是一个字符串,而不是一个集合,所以你不能应用Count().

我相信你想要的东西:(这种语法错了,但很接近)

from tan in TANS
group tan by tan.ID into dups
where dups.Count() > 1
select dups.Key;
Run Code Online (Sandbox Code Playgroud)

更新(5年零下5天后):(谷歌有点奇怪问题并找到你写的答案..)这个问题的核心是LINQ语句试图建立一个SQL语句和数据库不知道如何将Count()应用于字符串.但是,如果对内存中的集合使用LINQ,那么它会将字符串视为IEnumerable,而Count()可以正常工作.


Dav*_*vid 5

詹姆斯的回答接近于我认为你想要的,如果你只是想让身份证的价值与他一致.如果您希望分配ID的对象尝试此操作.

var dupes = (from tan in TANS
             group tan by tan.ID.ToString() into duplicates
             where duplicates.Count() > 1
             select duplicates.Select(d => d)).SelectMany(d => d);
Run Code Online (Sandbox Code Playgroud)

不是LINQ中最干净的方法我敢肯定.如果我想出一个更干净的方法,我会在这里编辑它.SelectMany非常重要,因为它会使IGrouping中的对象列表变平.