我有一个MVC3 C#.Net网络应用程序.我有以下字符串数组.
- public static string[] HeaderNamesWbs = new[]
- {
- WBS_NUMBER,BOE_TITLE,SOW_DESCRIPTION,HARRIS_WIN_THEME,COST_BOGEY
- };
我想在另一个循环中找到给定条目的索引.我以为这个列表会有一个IndexOf.我找不到它有任何想法吗?
解决方法
那么你可以使用Array.IndexOf:
- int index = Array.IndexOf(HeaderNamesWbs,someValue);
或者只是将HeaderNamesWbs声明为IList< string>而是 – 如果你想要的话,它仍然可以是一个数组:
- public static IList<string> HeaderNamesWbs = new[] { ... };
请注意,我不鼓励您将数组暴露为public static,甚至公开静态readonly.你应该考虑ReadOnlyCollection:
- public static readonly ReadOnlyCollection<string> HeaderNamesWbs =
- new List<string> { ... }.AsReadOnly();
如果你想要这个IEnumerable< T>,你可以使用:
- var indexOf = collection.Select((value,index) => new { value,index })
- .Where(pair => pair.value == targetValue)
- .Select(pair => pair.index + 1)
- .FirstOrDefault() - 1;
(1和-1是这样的,它将返回-1为“missing”,而不是0)