2016-01-23 56 views
2

給定一個集合Book,並且每個Book都有一個Store集合。使用Linq,我如何將其映射到具有Book集合的Store集合?與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; 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; } 
} 

回答

0

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

謝謝你試圖幫助我克服這個心理障礙。雖然這種解決方案存在問題。您需要重寫Object.Equals和Object.GetHashCode才能調用Distinct()來按預期的方式工作。我在過去http://stackoverflow.com/a/9601805/525558回答了這個問題。 – Craig

+0

我會考慮如何克服這一點,我會再次評論和編輯我的答案,如果有什麼合適的東西來到我的腦海:) –

+0

看看我發表的評論中的鏈接。它顯示了重寫Equals和GetHashCode。這樣做可以讓你定義平等的確定方式。除此之外,您還可以執行'IEquatable '來改善性能,正如所建議的那樣。再次非常感謝您花時間回答我的問題:) – Craig