Given
IList indexes;
ICollection collection;
What is the most elegant way to extract all T in
Several good suggestions here already, I'll just throw in my two cents.
int counter = 0;
var x = collection
.Where((item, index) =>
counter < indices.Length &&
index == indices[counter] &&
++counter != 0);
edit: yah, didn't think it through the first time around. the increment has to happen only when the other two conditions are satisfied..
Here's a faster version:
IEnumerable<T> ByIndices<T>(ICollection<T> data, IList<int> indices)
{
int current = 0;
foreach(var datum in data.Select((x, i) => new { Value = x, Index = i }))
{
if(datum.Index == indices[current])
{
yield return datum.Value;
if(++current == indices.Count)
yield break;
}
}
}
You could do it in an extension method:
static IEnumerable<T> Extract<T>(this ICollection<T> collection, IList<int> indexes)
{
int index = 0;
foreach(var item in collection)
{
if (indexes.Contains(index))
yield item;
index++;
}
}
public static IEnumerable<T> WhereIndexes<T>(this IEnumerable<T> collection, IEnumerable<int> indexes)
{
IList<T> l = new List<T>(collection);
foreach (var index in indexes)
{
yield return l[index];
}
}
Maybe I'm missing something, but what's wrong with just:
indexes.Select( (index => values[index]))
I would use an extension Method
public static IEnumerable<T> Filter<T>(this IEnumerable<T> pSeq,
params int [] pIndexes)
{
return pSeq.Where((pArg, pId) => pIndexes.Contains(pId));
}