Linq OrderedQueryAble Error

喜你入骨 提交于 2020-01-05 08:20:09

问题


First Thing's First I have a class to manipulate some data through a linq variable:

public class Result
{
    public bool LongerThan10Seconds { get; set; }
    public int Id { get; set; }
    public DateTime CompletionTime { get; set; }
}

Then in a Separate class I'm using this to grab info from a linq var

using (var data = new ProjectEntities())
{
    Result lastResult = null;
    List<Result> dataResults = new List<Result>();

    foreach(var subResult in data.Status.Select(x => x.ID).Distinct().Select(Id => data.Status.Where(x => x.ID == Id).OrderBy(x => x.Time)))
    {
        if (lastResult != null)
        {
            if (subResult.CompletionTime.Subtract(lastResult.CompletionTime).Seconds > 10)
                dataResults.Add(subResult);
        }
        lastResult = subResult;
    }

however I get the error:

Linq.IOrderedQueryAble does not contain a definition for 'CompletionTime' and no Extension method 'CompletionTime' accepting a first argument of type 'System.Linq.IOrderedQueryable.

Is anyone able to provide a solution to get around this would be much appreciated been trying to figure it out for a while but seems a bit difficult in terms of a DateTime Variable.


回答1:


Your problem is that subResult holds an IOrderedQueryable (presumably an IOrderedQueryable<Result>) rather than a Result.

You have this in the foreach: var subResult in data.Status.Select(x => x.ID).Distinct().Select(Id => data.Status.Where(x => x.ID == Id).OrderBy(x => x.Time)). Notice what's inside the Select: Id => data.Status.Where(x => x.ID == Id).OrderBy(x => x.Time). That will return an IOrderedQueryable<T>, not a T (where T is whatever type is in the data.Status collection).

You need to either get a single value out of that IOrderedQueryable, using First() or some similar method, like this:
var subResult in data.Status.Select(x => x.ID).Distinct().Select(Id => data.Status.Where(x => x.ID == Id).OrderBy(x => x.Time).First())

... or flatten your IEnumerable<IQueryable<T>> to an IEnumerable<T>: var subResult in data.Status.Select(x => x.ID).Distinct().SelectMany(Id => data.Status.Where(x => x.ID == Id).OrderBy(x => x.Time))

Edit: You may also be having an issue where C# is uncertain what type the var subResult is. If they're all Result type objects, try replacing var subResult with Result subResult.




回答2:


Looks like you have to use SelectMany instead your second Select method call

data.Status.Select(x => x.ID).Distinct()
    .SelectMany(Id => data.Status.Where(x => x.ID == Id).OrderBy(x => x.Time))


来源:https://stackoverflow.com/questions/20710957/linq-orderedqueryable-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!