tags:

views:

36

answers:

2

I'd like to use Linq to XML to output a sorted list each element should contain a value and its index on that list.

In other words I would like to do something like this (xml stuff was striped out):

 var Sample = new[] { "4", "3", "2", "1" }.AsQueryable();
 var r = (from o in Sample orderby o select new {obj=o, idx=?});

I'm not sure how to calculate idx.

Is that possible or should I use foreach loop?

+2  A: 

You could use a foreach loop, or you could use the overload of Select with this signature:

public static IEnumerable<TResult> Select<TSource, TResult>(
    this IEnumerable<TSource> source,
    Func<TSource, int, TResult> selector
)

This version of Select will pass the index of the item in the enumeration to you.

You would call it like this:

var Sample = new[] { "4", "3", "2", "1" };
var r = Sample.OrderBy(t => t).Select((t, i) => new {obj = t, idx = i});
casperOne
+1  A: 

I don't believe it's easy to achieve that with the query syntax. However if you use the lambda style query approach it's doable with the overload of select which passes the index as the second parameter.

var r = Sample.OrderBy(x => x).Select((o,i) => new { obj=o, idx=i});
JaredPar