c# Array.FindAllIndexOf 其中FindAll IndexOf [英] c# Array.FindAllIndexOf which FindAll IndexOf

查看:23
本文介绍了c# Array.FindAllIndexOf 其中FindAll IndexOf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 c# 有 Array.FindAllArray.IndexOf.

I know c# has Array.FindAll and Array.IndexOf.

是否有返回 int[]Array.FindAllIndexOf?

推荐答案

string[] myarr = new string[] {"s", "f", "s"};

int[] v = myarr.Select((b,i) => b == "s" ? i : -1).Where(i => i != -1).ToArray();

这将返回 0, 2

如果数组中不存在该值,则返回一个 int[0].

If the value does not exist in the array then it will return a int[0].

为它做一个扩展方法

public static class EM
{
    public static int[] FindAllIndexof<T>(this IEnumerable<T> values, T val)
    {
        return values.Select((b,i) => object.Equals(b, val) ? i : -1).Where(i => i != -1).ToArray();
    }
}

并称之为

string[] myarr = new string[] {"s", "f", "s"};

int[] v = myarr.FindAllIndexof("s");

这篇关于c# Array.FindAllIndexOf 其中FindAll IndexOf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆