计算数组数组中的元素等于指定值

时间:2017-06-15 15:03:08

标签: c# linq enumerable

我有数组数组。假设我想计算所有9个元素中的元素等于"a"

string[][] arr = new string[3][] {
    new string[]{"a","b","c"},
    new string[]{"d","a","f"},
    new string[]{"g","a","a"}
};

如何使用可枚举扩展方法(CountWhere等)来实现?

2 个答案:

答案 0 :(得分:3)

您可以使用SelectMany将所有数组展平为单个字符串序列,然后使用接受谓词的Count扩展名:

arr.SelectMany(a => a).Count(s => s == "a")

答案 1 :(得分:2)

您只需要一种方法来迭代矩阵的子元素,您可以使用SelectMany()执行此操作,然后使用Count()

// In this example I'll be assuming that 'dg' is an entity
// and that 'a', 'b' and 'c' are its attributes
// since, remember, Doctrine is designed specifically for using entities
// and make abstraction of the whole table model in your database

// First we'll create your QueryBuilder instance $qb
$qb = $this->createQueryBuilder('dg');

// Then we add our statements to the QueryBuilder instance
$qb
    ->where($qb->eq('dg.a', 1))
    ->andWhere($qb->expr()->orX(
        $qb->expr()->gt('dg.a', 1),
        $qb->expr()->eq('dg.b', 2)
    ))
    ->andWhere($qb->expr()->orX(
        $qb->expr()->gt('dg.a', 1),
        $qb->expr()->eq('dg.c', 3)
    ))
;

// Now you can use the QueryBuilder instance to, for instance, 
// have it do getResult (which in this case will return an array of 'dg' entities)
return $qb->getQuery()->getResult();

产:

int count = arr.SelectMany(x => x).Count(x => x == "a");

或者你可以Sum()计算每一行Count()的计数,例如:

csharp> arr.SelectMany(x => x).Count(x => x == "a");
4

再次制作:

int count = arr.Sum(x => x.Count(y => y == "a"));