简体   繁体   中英

Reversely query the List in C# LINQ

List<List<double>> Return(List<double> vector, int Z, int firstidx)
{            
    return vector.Reverse()
                 .Skip(firstidx)
                 .Take(Z)
                 .Select(i => vector.Reverse().Select(j => j != 0? i / j : 0.0).ToList())
                 .ToList();
}

I want to reversely query the List but there is some error in the .Reverse() and it said that:

Operator '.' cannot be applied oprand of type 'void'`.

Even I create a intermediate variable List<double> Reversevector = vector.Reverse().ToList();

So what the correct way to use .Reverse() in linq ?

Problem is you are using List.Reverse() method not the Enumerable.Reverse()

you have two options, either to call it as static method or explicit casting.

Enumerable.Reverse(vector)
          .Skip(firstidx)
           .Take(Z)
           .Select(i => Enumerable.Reverse(vector).Select(j => j != 0? i / j : 0.0).ToList())
           .ToList(); 

Use it like this, as List<T>.Reverse() doesn't return a new list :

vector.Reverse();
return vector.Skip(firstidx)
             .Take(Z)
             .Select(i => vector.Select(j => j != 0? i / j : 0.0).ToList())
             .ToList();

Copy the list to a local variable, or create an extension method similar to one below and modify your code.

public static IEnumerable<T> Reverse<T>(this IEnumerable<T> source)
{
   var reversedList = source.ToList();
   reversedList.Reverse();
   return reversedList;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM