c# - Linq distinct 无法正常工作

标签 c# linq linqpad

我在使用 linq 查询时遇到了一个奇怪的问题。我正在使用 LINQPad 4 进行一些使用正则表达式的查询,使用 LinqToSQL 作为 LinqPad 驱动程序。

这是我要进行的查询:

(from match in
from s in SystemErrors
select Regex.Match(s.Description, "...")
select new 
{
  FamilyCode = match.Groups["FamilyCode"].Value,
  ProductPrefix = match.Groups["ProductPrefix"].Value,
  BillingGroup = match.Groups["BillingGroup"].Value,
  Debtor = match.Groups["Debtor"].Value
}).Distinct()

如您所见,我正在尝试使用组从日志表中的文本描述中提取数据。查询有效,但 Distinct 不想工作,它为所有匹配项返回一行。

我读到 distinct 应该与匿名类型一起使用,匹配每个属性。更奇怪的是,distinct 确实做了一些事情,它按 FamilyCode 的字母顺序(然后按 ProductPrefix 等)对值进行排序。

有人知道为什么这不起作用吗? 谢谢

这是 LinqPad 的 SQL 选项卡中显示的内容:

DECLARE @p0 NVarChar(1000) = 'Big Regexp'
DECLARE @p1 NVarChar(1000) = 'FamilyCode'
DECLARE @p2 NVarChar(1000) = 'ProductPrefix'
DECLARE @p3 NVarChar(1000) = 'BillingGroup'
DECLARE @p4 NVarChar(1000) = 'Debtor'

SELECT DISTINCT [t2].[Description] AS [input], [t2].[value], [t2].[value2], [t2].[value3], [t2].[value4], [t2].[value5]
FROM (
    SELECT [t1].[Description], [t1].[value], @p1 AS [value2], @p2 AS [value3], @p3 AS [value4], @p4 AS [value5]
    FROM (
        SELECT [t0].[Description], @p0 AS [value]
        FROM [SystemError] AS [t0]
        ) AS [t1]
    ) AS [t2]

最佳答案

var result = from eachError in SystemErrors
             let match = Regex.Match(eachError.Description, "...")
             group eachError by new 
             {
              FamilyCode = match.Groups["FamilyCode"].Value,
              ProductPrefix = match.Groups["ProductPrefix"].Value,
              BillingGroup = match.Groups["BillingGroup"].Value,
              Debtor = match.Groups["Debtor"].Value
             }
             into unique
             select unique.key;

当您使用 Distinct() 时,它通过指向每个对象的指针而不是值来区分,因为 select new {} 是对象类型而不是值类型。尝试改用分组依据。

关于c# - Linq distinct 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4441659/

相关文章:

c# - 强制转换为无效枚举值 Enum.ToObject,不会引发异常,将 Enum 设置为 int

c# - Context.Items 在页面刷新/传输期间清除

c# - 基于书籍构建 LINQ 查询

c# - Linq 查询数据集中的多个数据表

c# - 如何将 System.Data.Entity.Infrastructure.DbQuery 类型转换为 System.Collections.Generic.List 类型?

LINQPad 命名空间文档

f# - 如何在我自己的代码中生成类似于 FSI 的 F# 类型签名?

c# - 在非泛型类 C# 中包装泛型类

c# - 如何使用 Swashbuckle 在 Swagger API 文档/OpenAPI 规范中包含子类?

c# - 在 Xamarin 中读取 XML 文件