LINQ OrderBy不起作用

Ale*_*dru 0 .net c# linq linq-to-objects exception

我有以下代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OrderByElementSubelement
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Place> places = new List<Place>();
            places.Add(new Place { Address = "Fifth Street", Score = 29, Houses = new List<House> { new House { Owner = "Mike", Score = 32 }, new House { Owner = "Bobby", Score = 3 } } });
            places.Add(new Place { Address = "Sixth Street", Score = 29, Houses = new List<House> { new House { Owner = "Mike", Score = 42 }, new House { Owner = "Ted", Score = 45 } } });
            places.Add(new Place { Address = "Seventh Street", Score = 29, Houses = new List<House> { new House { Owner = "Randy", Score = 84 }, new House { Owner = "William", Score = 1 } } });
            var placesWithMikesHouseOrderedByMikesHouseScore = places.Where(x => x.Houses.Where(y => y.Owner == "Mike").Count() > 0).OrderBy(x => x.Houses.Where(y => y.Owner == "Mike").Select(z => z.Score)).ToList();
        }

        public class Place
        {
            public string Address { get; set; }
            public int Score { get; set; }
            public List<House> Houses { get; set; }
        }

        public class House
        {
            public string Owner { get; set; }
            public int Score { get; set; }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

它抛出了这个异常:

An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll

Additional information: At least one object must implement IComparable.
Run Code Online (Sandbox Code Playgroud)

我正在尝试查询迈克的房子在那个地方以迈克的房子的分数排序(你可以从上面看到这个想法).一个地方有一个房子列表.重要提示:您可以假设没有个别业主可以在每个地方拥有多个房屋!

为什么它希望对象在这里实现IComparable,我该如何使这个查询工作?

Ree*_*sey 8

您的OrderBy函数返回一个集合,而不是单个元素:

OrderBy(x => x.Houses.Where(y => y.Owner == "Mike").Select(z => z.Score))
Run Code Online (Sandbox Code Playgroud)

您需要将其约束为分数,而不是IEnumerable<double>(如果Score是a double),即:

OrderBy(x => x.Houses.First(y => y.Owner == "Mike").Score)
Run Code Online (Sandbox Code Playgroud)

请注意,如果没有"Mike"作为所有者的房子,这将抛出,但是,您的第一个过滤器应该处理.