3

我只想从数组中查找前三个字符的字符串索引

我有一个月的数组

string[] arrayEnglishMonth = { "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER" };

如果我写

     int t_ciMonth=8;(AUGUST)
     int pos = Array.IndexOf(t_caMonth, arrayEnglishMonth[t_ciMonth - 1]);

但是如果我只想要前 3 个字符的索引,即 AUG,如何找到它?

4

6 回答 6

5
arrayEnglishMonth.ToList().FindIndex(s => s.Substring(0,3) == "AUG");
于 2013-08-05T06:38:43.683 回答
4

你有两个我能想到的选择:

  1. Linq只有看起来像这样的方法:

    var index = arrayEnglishMonth.Select((v, i) => new { v, i })
                                 .Where(c => c.v.StartsWith("AUG"))
                                 .Select(c => c.i)
                                 .First();
    

    这将首先遍历现有数组,创建可枚举的匿名对象,其中包含值和索引,其中传入的谓词Where返回 true,然后仅选择索引并从可枚举中获取第一个元素。

    演示

  2. Linq使用然后使用IndexOf方法找到相应的月份:

    var item = arrayEnglishMonth.First(c => c.StartsWith("AUG"));
    var index = Array.IndexOf(arrayEnglishMonth, item);
    

    演示

于 2013-08-05T06:39:37.567 回答
2

你可以用一点 Linq 做到这一点:

string[] arrayEnglishMonth = { "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER" };
string[] t_caMonth = { ... };
string search = arrayEnglishMonth[7].Substring(0, 3); // "AUG";
int pos = t_caMonth
    .Select((s, i) => new { s, i }).Dump()
    .Where(x => x.s == search)
    .Select(x => x.i)
    .DefaultIfEmpty(-1).First();

或者更简单地说:

int pos = t_caMonth.TakeWhile(s => s != search).Count();

虽然最后一个解决方案将返回t_caMonth.Length而不是-1如果没有找到匹配的元素。

于 2013-08-05T06:32:42.337 回答
0

如果t_caMonth有大写字母并且它的值只有 3 个字母,您可以使用:

 int pos = Array.IndexOf(t_caMonth, arrayEnglishMonth[t_ciMonth - 1]
     .Substring(0,3));

为了管理超过 3 个字符的大小写和值,您可以:

var pos = -1;
var sel = t_caMonth
    .Select((i, index) => new { index, i = i.ToUpper() })
    .Where(i => 
        i.i.Substring(0,3) == arrayEnglishMonth[t_ciMonth - 1].Substring(0, 3))
    .Select(i => i.index);
if (sel.Count() > 0)
    pos = sel.FirstOrDefault();

你也可以List<string>从你的t_caMonth数组中创建一个:

var pos2 = t_caMonth
    .ToList()
    .FindIndex(i => 
        i.ToUpper().Substring(0, 3) == 
            arrayEnglishMonth[t_ciMonth - 1].Substring(0, 3));
于 2013-08-05T06:29:42.057 回答
0

这是我实现这一目标的方法

string[] arrayEnglishMonth = { "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER" };
var searcheditem = arrayEnglishMonth.FirstOrDefault(item => item.Substring(0, 3) == "AUG");
if(searcheditem != null)
var itemIndex = Array.IndexOf(arrayEnglishMonth, searcheditem);

但@wdavo 答案更好

于 2013-08-05T06:40:39.657 回答
0

尝试使用以下,我认为它是最快的
Array.FindIndex(strArray, s => s.StartsWith("AUG"));

干杯。

于 2013-08-05T07:30:29.067 回答