c#Array.FindAllIndexOf哪个FindAll IndexOf
我知道c#有Array.FindAll
和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]。
制作它的扩展方法
public static class EM { public static int[] FindAllIndexof(this IEnumerable 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");
你可以这样写:
string[] someItems = { "cat", "dog", "purple elephant", "unicorn" }; var selectedItems = someItems.Select((item, index) => new{ ItemName = item, Position = index});
要么
var Items = someItems.Select((item, index) => new{ ItemName = item, Position = index}).Where(i => i.ItemName == "purple elephant");
阅读 : 使用LINQ获取给定项目的索引
搜索与指定谓词定义的条件匹配的元素,并在整个System.Array中返回事件的所有从零开始的索引。
public static int[] FindAllIndex(this T[] array, Predicate match) { return array.Select((value, index) => match(value) ? index : -1) .Where(index => index != -1).ToArray(); }
不,那里没有。 但是你可以编写自己的扩展方法 。
public static int[] FindAllIndexOf(this T[] a, Predicate match) { T[] subArray = Array.FindAll (a, match); return (from T item in subArray select Array.IndexOf(a, item)).ToArray(); }
然后,对于你的arrays,请调用它。
您可以使用findIndex循环给出索引
string[] arr = { "abc", "asd", "def", "abc", "lmn", "wer" }; int index = -1; do { index = Array.IndexOf(arr, "abc", index + 1); System.Console.WriteLine(index); } while (-1 != index);
我已经使用Nikhil Agrawal的答案来创建以下相关方法,这可能很有用。
public static List FindAllIndexOf(List values, List matches) { // Initialize list List index = new List (); // For each value in matches get the index and add to the list with indexes foreach (var match in matches) { // Find matches index.AddRange(values.Select((b, i) => Equals(b, match) ? i : -1).Where(i => i != -1).ToList()); } return index; }
其中列出了包含值的列表和包含要匹配的值的列表。 它返回带有匹配索引的整数列表。
我知道这个问题已经回答了,这只是另一种方式。 请注意我使用ArrayList
而不是int[]
// required using directives using System; using System.Collections; String inputString = "The lazy fox couldn't jump, poor fox!"; ArrayList locations = new ArrayList(); // array for found indexes string[] lineArray = inputString.Split(' '); // inputString to array of strings separated by spaces int tempInt = 0; foreach (string element in lineArray) { if (element == "fox") { locations.Add(tempInt); // tempInt will be the index of current found index and added to Arraylist for further processing } tempInt++; }