LINQ indexOf特定条目

我有一个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 – 如果您需要,它仍然可以是一个数组:

 public static IList HeaderNamesWbs = new[] { ... }; 

请注意,我不鼓励您将数组public staticpublic static ,甚至是public static readonly 。 你应该考虑ReadOnlyCollection

 public static readonly ReadOnlyCollection HeaderNamesWbs = new List { ... }.AsReadOnly(); 

如果你想要IEnumerable ,你可以使用:

 var indexOf = collection.Select((value, index) => new { value, index }) .Where(pair => pair.value == targetValue) .Select(pair => pair.index + 1) .FirstOrDefault() - 1; 

(+1和-1是为了“丢失”而不是0,它将返回-1)

我迟到了。 但我想分享我的解决方案。 Jon很棒,但我更喜欢简单的lambdas。

您可以扩展LINQ本身以获得您想要的。 这很简单。 这将允许您使用如下语法:

 // Gets the index of the customer with the Id of 16. var index = Customers.IndexOf(cust => cust.Id == 16); 

默认情况下,这可能不是LINQ的一部分,因为它需要枚举。 它不仅仅是另一个延迟选择器/谓词。

另请注意,这仅返回第一个索引。 如果你想要索引(复数),你应该在方法中返回一个IEnumerableyeild return index 。 当然不要返回-1。 在没有按主键过滤的情况下,这将非常有用。

  public static int IndexOf(this IEnumerable source, Func predicate) { var index = 0; foreach (var item in source) { if (predicate.Invoke(item)) { return index; } index++; } return -1; } 

Right List有IndexOf(),只是将它声明为ILIst而不是string[]

 public static IList HeaderNamesWbs = new List { WBS_NUMBER, BOE_TITLE, SOW_DESCRIPTION, HARRIS_WIN_THEME, COST_BOGEY }; int index = HeaderNamesWbs.IndexOf(WBS_NUMBER); 

MSDN: List(Of T).IndexOf方法(T)

如果要使用函数搜索List而不是指定项值,可以使用List.FindIndex(谓词匹配)。

请参阅https://msdn.microsoft.com/en-us/library/x1xzf2ca%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396