如何在锯齿状数组中查找唯一值

时间:2022-02-05 12:42:15

I would like to know how I can count the number of unique values in a jagged array.

我想知道如何计算锯齿状数组中唯一值的数量。

My domain object contains a string property that has space delimitered values.

我的域对象包含一个具有空格分隔值的字符串属性。

class MyObject
{
    string MyProperty; //e.g = "v1 v2 v3"
}

Given a list of MyObject's how can I determine the number of unique values?

给定一个MyObject列表,我如何确定唯一值的数量?

The following linq code returns an array of jagged array values. A solution would be to store a temporary single array of items, looped through each jagged array and if values do not exist, to add them. Then a simple count would return the unique number of values. However, was wondering if there was a nicer solution.

以下linq代码返回锯齿状数组值的数组。解决方案是存储临时的单个项目数组,循环遍历每个锯齿状数组,如果值不存在,则添加它们。然后一个简单的计数将返回唯一的值数。但是,想知道是否有更好的解决方案。

db.MyObjects.Where(t => !String.IsNullOrEmpty(t.MyProperty))
    .Select(t => t.Categories.Split(new char[] { ' ' },
        StringSplitOptions.RemoveEmptyEntries))
    .ToArray()

Below is a more readable example:

下面是一个更具可读性的例子:

array[0] = { "v1", "v2", "v3" }
array[1] = { "v1" }
array[2] = { "v4", "v2" }
array[3] = { "v1", "v5" }

From all values the unique items are v1, v2, v3, v4, v5.

从所有值中,唯一项为v1,v2,v3,v4,v5。

The total number of unique items is 5.

唯一商品的总数为5。

Is there a solution, possibly using linq, that returns either only the unique values or returns the number of unique values?

有没有一个解决方案,可能使用linq,只返回唯一值或返回唯一值的数量?

2 个解决方案

#1


8  

Yes, with LINQ this is quite simple. First use SelectMany to flatten the jagged array into an IEnumerable<string> containing all values and then call Distinct to select only unique values:

是的,使用LINQ这很简单。首先使用SelectMany将锯齿状数组展平为包含所有值的IEnumerable ,然后调用Distinct以仅选择唯一值:

IEnumerable<string> uniqueValues = array.SelectMany(x => x).Distinct();

If you want to count them then use Count:

如果你想计算它们,那么使用Count:

IEnumerable<string> uniqueValues = array.SelectMany(x => x).Distinct();
int uniqueCount = uniqueValues.Count();

#2


5  

A query expression method is

查询表达式方法是

var query = (from arr in array
             from value in arr
             select value).Distinct();

#1


8  

Yes, with LINQ this is quite simple. First use SelectMany to flatten the jagged array into an IEnumerable<string> containing all values and then call Distinct to select only unique values:

是的,使用LINQ这很简单。首先使用SelectMany将锯齿状数组展平为包含所有值的IEnumerable ,然后调用Distinct以仅选择唯一值:

IEnumerable<string> uniqueValues = array.SelectMany(x => x).Distinct();

If you want to count them then use Count:

如果你想计算它们,那么使用Count:

IEnumerable<string> uniqueValues = array.SelectMany(x => x).Distinct();
int uniqueCount = uniqueValues.Count();

#2


5  

A query expression method is

查询表达式方法是

var query = (from arr in array
             from value in arr
             select value).Distinct();