【问题标题】:How to query a datatable in C#如何在 C# 中查询数据表
【发布时间】:2021-12-01 17:18:51
【问题描述】:

我有一个包含许多列的数据表。其中两个是JobNumProcessNum。我想看看数据表中是否有重复记录。

通常在 SQL 中我会做一个

select count(jobnum) cntjobnum, JobNum, ProcessNum 
from table 
where jobnum = '1234' and processnum = '5678' 

在 C# 中是否有类似的方式(使用 C# 控制台应用程序)?

【问题讨论】:

  • 我没有从 CSV 文件填充数据表的 DBSet。表格CSVUtility
  • 哦,按jobnum,processnum分组

标签: linq datatable console-application


【解决方案1】:

我想看看数据表中是否有重复记录。

我认为你的 SQL 语句不会检测到重复记录,是吗?

没有 LINQ 方法可以检测 如果IEnumerable<...> 中有重复项。但是,有一些方法可以检测重复项。如果只想查找是否有重复,则在找到重复后继续处理其他元素的效率不是很高。因此,最有效的方法是在找到重复项后立即停止。

public static bool HasDuplicates<T>(this IEnumerable<T> source)
{
    return HasDuplicates(source, null);
}

public static bool HasDuplicates<T>(this IEnumerable<T> source,
    IEqualityComparer<T> comparer)
{
    if (source == null) throw new ArgumentNullException(...);

    // if null comparer, use the default comparer:
    if (comparer == null) comparer = EqualityComparer<T>.Default;

    HashSet<T> set = new HashSet<T>(comparer);
    foreach (T t in source)
    {
        if (set.Contains(t))
            return true; // found a duplicate
        else
            set.Add(t);
    }
    return false; // no duplicates found
}

如果要查找所有重复项,请考虑使用GroupBy,并使用完整项作为键。

IEnumerable<Product> products = ...
IEqualityComparer<Product> comparer = ... // or use default comparison

var duplicates = products.GroupBy(product => product, comparer)

    // keep only the groups that have more than one element
    .Where(group => group.Skip(1).Any())

    // from the remaining groups, take the key (which is the product
    .Select(group => group.Key);
    (key, elementsWithThisKey) => 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多