【发布时间】:2020-03-04 14:58:25
【问题描述】:
我似乎无法掌握如何做到这一点,也找不到简单的方法来解释它......所以我希望这个简化的例子能有意义。
得到一个对象列表:
public class FlatManyToMany
{
public string BookTitle { get; set; }
public int BookPages { get; set; }
public string ReaderName { get; set; }
public int ReaderAge { get; set; }
}
var flatManyToMany = new List<FlatManyToMany>();
flatManyToMany.Add(new FlatManyToMany { BookTitle = "How to Do This Double List", BookPages = 105, ReaderName = "Kyle", ReaderAge = 29 });
flatManyToMany.Add(new FlatManyToMany { BookTitle = "How to Do This Double List", BookPages = 105, ReaderName = "Bob", ReaderAge = 34 });
flatManyToMany.Add(new FlatManyToMany { BookTitle = "Gone With Jon Skeet", BookPages = 192, ReaderName = "Kyle", ReaderAge = 29 });
flatManyToMany.Add(new FlatManyToMany { BookTitle = "Gone With Jon Skeet", BookPages = 192, ReaderName = "James", ReaderAge = 45 });
flatManyToMany.Add(new FlatManyToMany { BookTitle = "Gone With Jon Skeet", BookPages = 192, ReaderName = "Brian", ReaderAge = 15 });
flatManyToMany.Add(new FlatManyToMany { BookTitle = "Why Is This So Hard?", BookPages = 56, ReaderName = "Kyle", ReaderAge = 29 });
flatManyToMany.Add(new FlatManyToMany { BookTitle = "Why Is This So Hard?", BookPages = 56, ReaderName = "James", ReaderAge = 45 });
flatManyToMany.Add(new FlatManyToMany { BookTitle = "Why Is This So Hard?", BookPages = 56, ReaderName = "Brian", ReaderAge = 15 });
flatManyToMany.Add(new FlatManyToMany { BookTitle = "Impostor Syndrome", BookPages = 454, ReaderName = "Kyle", ReaderAge = 29 });
flatManyToMany.Add(new FlatManyToMany { BookTitle = "Self Doubt and You", BookPages = 999, ReaderName = "Kyle", ReaderAge = 29 });
我需要的结果是两个对象列表的列表:
public class ResultDoubleList
{
public List<Book> Books { get; set; } = new List<Book>();
public List<Reader> Readers { get; set; } = new List<Reader>();
}
public class Book
{
public string Title { get; set; }
public int Pages { get; set; }
}
public class Reader
{
public string Name { get; set; }
public int Age { get; set; }
}
Book 在最终结果中应该只出现一次,但 Reader 可以出现多次。如果同一读者阅读了多本书,则可以将它们放在一起。
这是我需要的结果:
List<ResultDoubleList> results = new List<ResultDoubleList>();
result(1):
Books
How to Do This Double List 105
Readers
Kyle 29
Bob 34
result(2):
Books
Gone With Jon Skeet 192
Why Is This So Hard? 56
Readers
Kyle 29
James 45
Brian 15
result(3):
Books
Impostor Syndrome 454
Self Doubt and You 999
Readers
Kyle 29
因此,书籍列表和读者列表的不同组合是最终结果。这本书只出现一次,但读者可以出现不止一次。具有完全相同读者列表的书籍将被归为一组。
即使有人能告诉我这种类型的最终结果叫什么,我也会很感激。
【问题讨论】:
-
我认为
ReaderAge和BookPages需要定义为int。 -
@RufusL 你是对的。我的实际问题与书籍和读者无关,所以只是一个尽可能简化问题的示例。