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

2023-09-06 08:07:06 作者:小惡魔

我有一些问题想在CSHARP从数据集检索唯一值,这可能吗?

I'm having some issues trying to retrieve unique values from a DataSet in csharp, is that possible?

其实我在做这样的事情,获取数据集从一个Web服务:

Actually I'm doing something like this that gets a dataset from a webservice:

 webService.getInstructions(Username, Password, AppKey).Tables[0].Select(null, "account name asc");

因此​​,在这种情况下,我得到了一个帐户按字母顺序排列,但也有在该数据集的一些重复的行。

So in this case I get a alphabetical list from the accounts, but there are some duplicated rows in this dataset.

有没有什么办法,使具有独特的账号这个数据集返回值和排序按字母顺序的帐户名?

Is there any way to make this Dataset return values with unique "account number" and sort it alphabetically by "account name"?

东西代替 filterEx pression 将是非常好的,我认为。 :)

Something in place of the filterExpression would be very nice I think. :)

在此先感谢

推荐答案

我个人会更改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;
        }
    }
 
精彩推荐
图片推荐