gpt4 book ai didi

c# - Linq 至少一个对象必须实现 IComparable

转载 作者:太空狗 更新时间:2023-10-30 00:52:09 27 4
gpt4 key购买 nike

我正在尝试订购包含另一个实体列表的实体列表。我已经为所有实体实现了 IComparable,但仍然出现异常。我看到的所有示例都解决了您有一个列表并按该列表中的给定字段排序但没有列表列表的问题。对于下面的 Linq to Objects 以及 Linq to Entities,都会发生此问题。我错过了什么?

[TestClass]
public class OrderBy
{
[TestMethod]
public void OrderByTest()
{
var hobbies = new Collection<Hobby> { new Hobby { HobbyId = 1, Name = "Eating" }, new Hobby() { HobbyId = 2, Name = "Breathing" } };

var p1 = new Person
{
PersonId = 1,
Name = "A",
PersonHobbies = new Collection<PersonHobby> { new PersonHobby() { PersonHobbyId = 1}}
};
var p2 = new Person
{
PersonId = 2,
Name = "Z",
PersonHobbies = new Collection<PersonHobby> { new PersonHobby() { PersonHobbyId = 2 }}
};

var people = new List<Person> { p1, p2 };
var pplEnumerable = people.AsEnumerable();
pplEnumerable = pplEnumerable.OrderByDescending(r => r.PersonHobbies.OrderByDescending(p => p.Hobby.Name));
foreach (var person in pplEnumerable)
{
Console.WriteLine(person.Name);
}
}
public class Person : IComparable
{
public int PersonId { get; set; }
public string Name { get; set; }
public virtual ICollection<PersonHobby> PersonHobbies { get; set; }
public int CompareTo(object obj)
{
if (obj == null) return 1;
var otherPerson = obj as Person;
return PersonId.CompareTo(otherPerson.PersonId);
}
}
public class PersonHobby : IComparable
{
public int PersonHobbyId { get; set; }
public int HobbyId { get; set; }
public virtual Person Person{ get; set; }
public int PersonId { get; set; }
public virtual Hobby Hobby { get; set; }
public int CompareTo(object obj)
{
if (obj == null) return 1;
var otherPersonHobby = obj as PersonHobby;
return PersonHobbyId.CompareTo(otherPersonHobby.PersonHobbyId);
}
}
public class Hobby : IComparable
{
public int HobbyId { get; set; }
public string Name { get; set; }
public int CompareTo(object obj)
{
if (obj == null) return 1;
var otherHobby = obj as Hobby;
return HobbyId.CompareTo(otherHobby.HobbyId);
}
}
}

最佳答案

默认情况下,您不能对列表应用排序。您需要编写自定义类(类似 EquatableList 等)或使用 LINQ Except & Intersect 运算符来比较列表。

但是根据您的评论,如果您正在寻找 LINQ 等价物:

select * from Person p join PersonHobby ph 
on ph.PersonId = p.PersonId join Hobby h
on h.HobbyId = ph.HobbyId order by h.Name

那么可以这样实现:

var query = people.SelectMany(p => p.PersonHobbies)
.Join(hobbies, ph => ph.HobbyId, h => h.HobbyId,
(ph, h) => new
{
Person = ph.Person, PersonHobby = ph, Hobby = h
})
.OrderBy(r => r.Hobby.Name);

基本上,我们将 person、person hobbies 和 hobby 连接到键上,投影所有列并按 hobby.name 字段对其进行排序,如您的 SQL 中所述。

关于c# - Linq 至少一个对象必须实现 IComparable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23307566/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com