如何在LINQ中获得数组索引 [英] How to get an array index in LINQ
问题描述
我从两个单独的来源(我无法控制)获得两个字符串作为输入.第一个字符串strInput
将包含一个"X",其位置应等于pattern
字符串中元素的值.我需要pattern
中元素的索引.
我已经使用``for''循环在常规代码中工作了,但是想使用LINQ和/或lambda使其更加简洁.以下返回值4,但我需要的是索引,在这种情况下为"1".
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''.
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.
推荐答案
安妮,你好!
试试这个.
Hi Annie!
Try this.
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 (4)
string[] positions = pattern.Split(",");
//Create a temporary structure saving the positions along with their positions.
var result = positions.Select((s, i) => new { Pos = i, Str = s })
.Where(o => o.Str == place) //Pick the item with a position matching the input
.FirstOrDefault();
if (result != null)
{
var output = result.Pos;
}
此解决方案更为简洁,但请注意,它要求输入始终有效,因此您可能需要进行一些初始检查.
This solution is much more succinct, but note that it requires the input to always be valid, so you might want to do some initial checking.
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
int place = strInput.IndexOf("X"); // Get position of X (4)
var positions = pattern.Split(",").Select(s => int.Parse(s));
int result = positions.TakeWhile((p, i) => p != place)
.Count();
这篇关于如何在LINQ中获得数组索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!