使用Linq映射模型

时间:2016-01-23 18:43:10

标签: c# linq

给出一个集合Book和每本书都有一个Store集合。使用Linq,我如何将其映射到具有Book?

集合的Store集合

目标类与原始类不同。

转换定义为:

的Book集合
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; }
}

2 个答案:

答案 0 :(得分:1)

这应该可以解决问题:

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);
}

您可以构建所需的任何数据结构,而不是匿名数据类型(new { Store = ..., Books = ...}),例如Store类的一个对象,包含一系列书籍)

答案 1 :(得分:0)

按商店完成分组,然后为每个商店填充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()
});