且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#中的数据集 - 获取独特价值的基础上列

更新时间:2023-02-16 15:34:03

我个人会更改Web服务要做到这一点的过滤,并在服务器排序以降低带宽需求,很可能返回简单的数据类型或自定义类(未数据表或类似的话)。但LINQ会做的工作......(更新在重新阅读的问题)

Personally I'd change the web-service to do this filtering and sorting at the server to reduce bandwidth needs, probably returning a simple data-type or custom class (not DataTable or anything similar). But LINQ would do the job... (updated after re-reading the question)

var rows = dataset.Tables[0].AsEnumerable()
    .DistinctBy(row => row.Field<string>("account number"))
    .OrderBy(row => row.Field<string>("account name"))
    .ToArray();

使用自定义的 DistinctBy 方法:

    static IEnumerable<TSource> DistinctBy<TSource, TValue>(
        this IEnumerable<TSource> source,
        Func<TSource, TValue> selector)
    {
        HashSet<TValue> unique = new HashSet<TValue>();
        foreach (var item in source)
        {
            if (unique.Add(selector(item))) yield return item;
        }
    }