问题
I have an MVC3 C#.Net web app. I have the below string array.
public static string[] HeaderNamesWbs = new[]
{
WBS_NUMBER,
BOE_TITLE,
SOW_DESCRIPTION,
HARRIS_WIN_THEME,
COST_BOGEY
};
I want to find the Index of a given entry when in another loop. I thought the list would have an IndexOf. I can't find it. Any ideas?
回答1:
Well you can use Array.IndexOf
:
int index = Array.IndexOf(HeaderNamesWbs, someValue);
Or just declare HeaderNamesWbs
as an IList<string>
instead - which can still be an array if you want:
public static IList<string> HeaderNamesWbs = new[] { ... };
Note that I'd discourage you from exposing an array as public static
, even public static readonly
. You should consider ReadOnlyCollection
:
public static readonly ReadOnlyCollection<string> HeaderNamesWbs =
new List<string> { ... }.AsReadOnly();
If you ever want this for IEnumerable<T>
, you could use:
var indexOf = collection.Select((value, index) => new { value, index })
.Where(pair => pair.value == targetValue)
.Select(pair => pair.index + 1)
.FirstOrDefault() - 1;
(The +1 and -1 are so that it will return -1 for "missing" rather than 0.)
回答2:
I'm late to the thread here. But I wanted to share my solution to this. Jon's is awesome, but I prefer simple lambdas for everything.
You can extend LINQ itself to get what you want. It's fairly simple to do. This will allow you to use syntax like:
// Gets the index of the customer with the Id of 16.
var index = Customers.IndexOf(cust => cust.Id == 16);
This is likely not part of LINQ by default because it requires enumeration. It's not just another deferred selector/predicate.
Also, please note that this returns the first index only. If you want indexes (plural), you should return an IEnumerable<int>
and yeild return index
inside the method. And of course don't return -1. That would be useful where you are not filtering by a primary key.
public static int IndexOf<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) {
var index = 0;
foreach (var item in source) {
if (predicate.Invoke(item)) {
return index;
}
index++;
}
return -1;
}
回答3:
Right List
has IndexOf(), just declare it as ILIst<string>
rather than string[]
public static IList<string> HeaderNamesWbs = new List<string>
{
WBS_NUMBER,
BOE_TITLE,
SOW_DESCRIPTION,
HARRIS_WIN_THEME,
COST_BOGEY
};
int index = HeaderNamesWbs.IndexOf(WBS_NUMBER);
MSDN: List(Of T).IndexOf Method (T)
回答4:
If you want to search List with a function rather than specifying an item value, you can use List.FindIndex(Predicate match).
See https://msdn.microsoft.com/en-us/library/x1xzf2ca%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
来源:https://stackoverflow.com/questions/9300169/linq-indexof-a-particular-entry