2016-08-22 56 views
0

沒有輸入和輸出就很難解釋這一點。我做了一個簡單的汽車示例以避免不必要的項目細節。SelectMany的相反之處是什麼?

我有這樣的名單:

List<car> cars = new List<car>() 
{ 
    new car() { carname = "bmw", carwheels = new List<int>() { 1, 2, 3, 4 } }, 
    new car() { carname = "cadillac", carwheels = new List<int>() { 1, 2, 3, 4 } }, 
    new car() { carname = "mustang", carwheels = new List<int>() { 1, 2, 3, 4 } } 
}; 

我想這個輸出,擴展類:

{ 
    { carname = "bmw", carwheel = 1 }, 
    { carname = "bmw", carwheel = 2 }, 
    { carname = "bmw", carwheel = 3 }, 
    { carname = "bmw", carwheel = 4 }, 
    { carname = "cadillac", carwheel = 1 }, 
    { carname = "cadillac", carwheel = 2 }, 
    { carname = "cadillac", carwheel = 3 }, 
    { carname = "cadillac", carwheel = 4 }, 
    { carname = "mustang", carwheel = 1 }, 
    { carname = "mustang", carwheel = 2 }, 
    { carname = "mustang", carwheel = 3 }, 
    { carname = "mustang", carwheel = 4 } 
} 

有沒有辦法通過IEnumerable的擴展方法的投影來做到這一點?與SelectMany()相反的東西。

+11

爲什麼相反,是不是'SelectMany'確實是什麼? –

+0

@TimSchmelter - 根據我的理解,'SelectMany()'會將最下面的列表展平,並將它們拼成單打,每個列表都有一個車輪列表。是否有另一個重載SelectMany()我應該學習? – BeemerGuy

+0

這不是'SelectMany'的反義詞,這*是*'SelectMany'。 – dasblinkenlight

回答

6

這不是對面SelectMany(),但確切SelectMany()是什麼。可以這樣實現這一點:每款車的

var result = cars.SelectMany(c => 
      c.carwheels.Select(w => new 
      { 
       carname = c.carname, 
       carwheel = w 
      })).ToList(); 

Select項目輪子一個新的對象(在我的匿名類型的代碼與您指定的屬性)。外部的SelectMany()將這些序列展平成一個列表。

+0

是的,這一直在旋轉我的頭一段時間,你是對的 - 抱歉我的誤導標題。這正是我需要的! – BeemerGuy

-2

也許這個解決方案會有幫助嗎?這將分裂您的IEnumerable到IEnumerable的固定大小的IEnumerable的

public static class EnumerableExtension 
{ 
    private static IEnumerable<T> GetChunk<T>(IEnumerator<T> source, int size) 
    { 
     yield return source.Current; 

     for (int i = 1; i < size; i++) 
     { 
      if (source.MoveNext()) 
      { 
       yield return source.Current; 
      } 
      else 
      { 
       yield break; 
      } 
     } 
    } 

    public static IEnumerable<IEnumerable<T>> SplitToChunks<T>(this IEnumerable<T> source, int size) 
    { 
     if (size < 1) 
     { 
      throw new ArgumentOutOfRangeException(); 
     } 

     using (var enumerator = source.GetEnumerator()) 
     { 
      while (enumerator.MoveNext()) 
      { 
       yield return GetChunk(enumerator, size); 
      } 
     } 
    } 

} 

對不起,沒有正確讀取的問題)

2

這是罕見的情況下,我找到詳細的LINQ語法更具可讀性之一:

var query = from car in cars 
      from carwheel in car.carwheels 
      select new { car.carname, carwheel }; 
相關問題