score:32
You could easily add your own extension method:
public static IEnumerable<int> IndexesWhere<T>(this IEnumerable<T> source, Func<T, bool> predicate)
{
int index=0;
foreach (T element in source)
{
if (predicate(element))
{
yield return index;
}
index++;
}
}
Then use it with:
string[] s = {"zero", "one", "two", "three", "four", "five"};
var x = s.IndexesWhere(t => t.StartsWith("t"));
score:0
I discussed this interesting problem with a colleague and at first I thought JonSkeet's solution was great, but my colleague pointed out one problem, namely that if the function is an extension to IEnumerable<T>
, then it can be used where a collection implements it.
With an array, it's safe to say the order produced with foreach
will be respected (i.e. foreach
will iterate from first to last), but it would not necessarily be the case with other collections (List, Dictionary, etc), where foreach
would not reflect necessarily "order of entry". Yet the function is there, and it can be misleading.
In the end, I ended up with something similar to tvanfosson's answer, but as an extension method, for arrays:
public static int[] GetIndexes<T>(this T[]source, Func<T, bool> predicate)
{
List<int> matchingIndexes = new List<int>();
for (int i = 0; i < source.Length; ++i)
{
if (predicate(source[i]))
{
matchingIndexes.Add(i);
}
}
return matchingIndexes.ToArray();
}
Here's hoping List.ToArray
will respect the order for the last operation...
score:1
How about this? It's similar to the original poster's but I first select the indexes and then build a collection which matches the criteria.
var x = s.Select((a, i) => i).Where(i => s[i].StartsWith("t"));
This is a tad less efficient than some of the other answers as the list is fully iterated over twice.
score:2
There is also FindIndex method in Collection List for which you create a delete method which can return the index from the collection. you can refer to the following link in msdn http://msdn.microsoft.com/en-us/library/x1xzf2ca.aspx.
score:5
Seems fine to me. You might save a couple characters by changing the select to:
.Select((Value, Index) => new {Value, Index})
score:6
If you're just using the example as a way to learn LINQ, ignore this post.
It's not clear to me that LINQ is actually the best way to do this. The code below seems like it would be more efficient since no new anonymous type needs to be created. Granted, your example may be contrived and the technique might be more useful in a different context, for example in a data structure where it could take advantage of an index on value, but the code below is reasonably straight-forward, understandable (no thought required) and arguably more efficient.
string[] s = {"zero", "one", "two", "three", "four", "five"};
List<int> matchingIndices = new List<int>();
for (int i = 0; i < s.Length; ++i)
{
if (s[i].StartWith("t"))
{
matchingIndices.Add(i);
}
}
Source: stackoverflow.com
Related Query
- Getting a collection of index values using a LINQ query
- Getting Row Index for LINQ Query using Custom Object
- How to select values within a provided index range from a List using LINQ
- Query and updating a property in a collection using LINQ
- Using LINQ to change values in collection
- Getting common values in two array issue using LINQ
- Query a collection using PropertyInfo object in LINQ
- Get array index values of the top 1000 largest entries inside an array using LINQ
- How can I write the following code more elegantly using LINQ query syntax?
- Getting Table's Row Index Using LINQ
- Query on encrypted values using LINQ
- Getting several node values using LINQ
- ASP.NET : select multiple values in query using Linq
- LINQ RavenDB sub collection query using Any, cannot include non-indexed variables in query
- LINQ to XML: filter a query using XElement.Attributes() collection with both XName and Value
- Linq sub query when using a repository pattern with EF code first
- How to write LINQ query for getting object from another object using C#?
- Using LINQ query result for data source for GridControl c#
- Getting unique values using Linq to Entities
- how to get two column values in a single query using linq to entities
- Filter Parent Collection Using Criteria in Child Collection via a Linq Query
- How to get the index of int array when using linq query
- Getting 'Data source is an invalid type' when binding Linq query to Gridview
- How can I check the number of calls to the database in LINQ query when using .NET Core and Code First?
- How to return values from a LINQ query and display them in a table using C#, ASP.NET MVC and Entity Framework
- Filter linq query results using values from a list
- Using Max in LINQ query - null values in the list
- Linq Using Child Collection in Query
- Getting Rounded Values in the final result of Linq Query
- How to query a Datatable using LINQ and add values to a List?
More Query from same tag
- custom string sorter
- C# Add Objects Derived Of A Common Interface to a Collection in a Single Method
- Automapping double nested IEnumerable
- Linq Update to SQL
- ExecuteQuery returns empty collection when there is only a single result
- Passing A DbSet<T> created at runtime via reflection to Queryable
- LINQ's Distinct() on a particular property
- c#, update child node in XML
- Create an dyanamic list from a List(of Class) with where condition
- c# LINQ joining to comma separated string
- Is there an equivalent to the F# Seq.windowed in C#?
- What's The Best Way To Remove Duplicate Rows Based On A Row Item In A DataTable With VB.Net?
- How to Select subset of columns from SingleOrDefault LINQ query in EF
- Getting MethodInfo without name as string
- Get average of the difference in datetime columns?
- Linq ForEach() not populating fields
- DataTable Select Method "not intended to be used"?
- Can I specify Queryable.GroupBy (instead of Enumerable.GroupBy) in query expression syntax
- Hierarchical list based on parent_id using C# / LINQ
- LINQ merging multiple lists
- Linq GroupBy and Join
- How to construct a specific linq query?
- Update & Insert into database using Odata service and linq
- Tuples in where condition
- Fastest method to Fill Data in Nested List
- Linq for objects
- Delete a context record from grid in kendo UI using LINQ
- Converting a Linq expression tree that relies on SqlMethods.Like() for use with the Entity Framework
- multiple where in linq based on parameters value
- Select statement taking a long time