C# Linq映射模型
给出一本藏书,每本藏书都有一个收藏库。使用Linq,我如何将其映射到包含书籍集合的商店集合 目标类与源类不同 转换定义为以下内容的书籍集合:C# Linq映射模型,c#,linq,C#,Linq,给出一本藏书,每本藏书都有一个收藏库。使用Linq,我如何将其映射到包含书籍集合的商店集合 目标类与源类不同 转换定义为以下内容的书籍集合: public class Book { int Id { get; set; } string Name { get; set; } Store[] Stores { get; set; } } public class Store { int Id { get; set; } string Name { get;
public class Book
{
int Id { get; set; }
string Name { get; set; }
Store[] Stores { get; set; }
}
public class Store
{
int Id { get; set; }
string Name { get; set; }
}
public class DestinationStore
{
int Id { get; set; }
string Name { get; set; }
Book[] Books { get; set; }
}
public class DestinationBook
{
int Id { get; set; }
string Name { get; set; }
}
到定义为以下内容的存储集合:
public class Book
{
int Id { get; set; }
string Name { get; set; }
Store[] Stores { get; set; }
}
public class Store
{
int Id { get; set; }
string Name { get; set; }
}
public class DestinationStore
{
int Id { get; set; }
string Name { get; set; }
Book[] Books { get; set; }
}
public class DestinationBook
{
int Id { get; set; }
string Name { get; set; }
}
这应该可以做到:
public class Book
{
public int Id { get; set; }
public string Name { get; set; }
public Store[] Stores { get; set; }
}
public class Store
{
public int Id { get; set; }
public string Name { get; set; }
}
public static void Main()
{
List<Book> books = new List<Book>();
var stores = books.SelectMany(x => x.Stores) // flatMap method, returns a collection of stores
.Distinct() // only keep different stores
.Select(x => // foreach store
new { // create a new object
Store = x, // that contains the store
Books = books.Where(book => book.Stores.Contains(x)).ToList() // and a list of each book that is in the store
})
.ToList();
Console.WriteLine(stores);
}
公共课堂教材
{
公共int Id{get;set;}
公共字符串名称{get;set;}
公共存储[]存储{get;set;}
}
公共类商店
{
公共int Id{get;set;}
公共字符串名称{get;set;}
}
公共静态void Main()
{
列表书籍=新列表();
var stores=books.SelectMany(x=>x.stores)//flatMap方法,返回存储的集合
.Distinct()//只保留不同的存储
.Select(x=>//foreach存储
新建{//创建一个新对象
Store=x,//包含存储的
Books=Books.Where(book=>book.Stores.Contains(x)).ToList()//以及存储中每本书的列表
})
.ToList();
控制台写入线(存储);
}
除了匿名数据类型(新的{Store=…,Books=…}),你可以建立你想要的任何数据结构,例如,你的Store类的一个对象,它包含一系列的书)最后按Store分组,然后为每个Store填充Store.Books。我想可能有一个更优雅的解决方案
var stores = books.SelectMany(x => x.Stores).GroupBy(x => new
{
x.Id,
x.Name
}).Select(x => new DestinationStore
{
Id = x.Key.Id,
Name = x.Key.Name,
Books = books.Where(bookFilter => bookFilter.Stores.Select(store => store.Id).Contains(x.Key.Id))
.Select(book => new DestinationBook
{
Id = book.Id,
Name = book.Name
}).ToArray()
});
谢谢你帮我克服这个心理障碍。尽管这个解决方案存在问题。您需要重写
Object.Equals
和Object.GetHashCode
,以便调用Distinct()
按预期工作。我过去曾回答过一个关于这个问题的问题。我会考虑如何克服这个问题,如果我想到合适的答案,我会再次发表评论并编辑我的答案:)看看我在评论中发布的链接。它显示Equals和GetHashCode的重写。这样做允许您定义如何确定相等。除此之外,您还可以按照建议实施IEquatable
,以提高性能。再次感谢您抽出时间回答我的问题:)