Click here to Skip to main content
15,892,059 members

How to get an array index in LINQ

AnnieMacD asked:

Open original thread
I get two strings as input from two separate sources (over which I have no control). The first string strInput will contain one 'X', the position of which should be equal to the value of an element in the pattern string. I need the index of the element in pattern.

I've got it working in regular code using 'for' loops but would like to use LINQ and/or lambdas to make it more succinct. The following returns the value 4, but what I need is the index, which in this case is '1'.

C#
string strInput = "    X       ";           // String from form (this is 4 spaces followed by X followed by n spaces
string pattern = "0,4,6,8,11";              // String containing matching positions of X in string

string place = strInput.IndexOf("X").ToString();        // Get position of X
string[] positions = pattern.Split(',');

var thisIndex = from pos in positions
                where (pos == place)
                select pos.First();

foreach (var x in thisIndex)
{
    Console.WriteLine("This is the index of X: {0}", x);
    Console.ReadLine();
}


Any help would be appreciated.
Tags: C#, .NET, LINQ

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the http://www.codeproject.com/info/cpol10.aspx.



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900