Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# Array.FindAllIndexOf which FindAll IndexOf

Tags:

arrays

c#

indexof

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

Is there a Array.FindAllIndexOf which returns int[]?

like image 708
Eric Yin Avatar asked May 04 '12 06:05

Eric Yin


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

What is C and C++ meaning?

C is a function driven language because C is a procedural programming language. C++ is an object driven language because it is an object oriented programming. Function and operator overloading is not supported in C. Function and operator overloading is supported by C++. C is a function-driven language.


2 Answers

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

This will return 0, 2

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

make an extension method of it

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();     } } 

and call it like

string[] myarr = new string[] {"s", "f", "s"};  int[] v = myarr.FindAllIndexof("s"); 
like image 149
Nikhil Agrawal Avatar answered Sep 23 '22 14:09

Nikhil Agrawal


You can write something like :

string[] someItems = { "cat", "dog", "purple elephant", "unicorn" };  var selectedItems = someItems.Select((item, index) => new{     ItemName = item,     Position = index}); 

or

var Items = someItems.Select((item, index) => new{     ItemName = item,     Position = index}).Where(i => i.ItemName == "purple elephant"); 

Read : Get the index of a given item using LINQ

like image 41
Pranay Rana Avatar answered Sep 22 '22 14:09

Pranay Rana