2017-10-04 98 views
0

起初,我有一個項目清單:LINQ:轉換分組列表進入新的名單

List<Item> mySourceList; 

哪個項目是:

項目類

public class Item 
{ 
    public DateTime Date 
    { 
    get; 
    set; 
    } 
    public string ProviderID 
    { 
    get; 
    set; 
    }  
    public List<AnotherClass> listOfitems 
    { 
    get;  
    set; 
    } 
    public byte[] Img 
    { 
    get; 
    set; 
    } 
    // Other properties 

    public long GroupID 
    { 
    get; 
    set; 
    } 
} 

我需要組mySourceList的ProviderID和日期,所以我做如下:

var grp = mySourceList .GroupBy(e => new { e.ProviderID, e.Date }); 

然後我在這個分組名單進行一些opertions:

int groupId = 1; 
foreach (var group in grp) 
{ 
    int id = group.Count() > 1 ? groupId++ : 0; 

    // Loop through each item within group 
    foreach (var item in group) 
     item.GroupID = id; 
} 

最後,我想mySourceList列表轉換成一個新的,新人們必須再次列出,所以我下面想,但它不工作:

List<Item> myDestList = grp.ToList<Item>(); 

我該如何轉換爲List?

我使用Visual Studio 2008和.NET框架3.5 SP1

回答

3

使用SelectMany擴展方法。
grpIEnumerable<IGrouping<'a, Item>>類型 - 所以它是某種列表的列表。
而且你需要所有物品的退貨清單。

List<Item> myDestList = grp.SelectMany(g => g).ToList(); 

另一種方法是使用您的原始列表,因爲您的代碼更新已經存在的項目。

+0

最後我有循環的令牌優勢,請參閱我的答案。無論如何,你的解決方案完美工作,我喜歡它。 – user1624552

0

我已經趁着操作中循環更新分組的列表如下進行:

List<Item> groupedList = new List<Item>(); 

int groupId = 1; 
foreach (var group in grp) 
{ 
    int id = group.Count() > 1 ? groupId++ : 0; 

    // Loop through each item within group 
    foreach (var item in group) 
    { 
     item.GroupID = id; 
     groupedList.add(Item); 
    } 
} 

myDestList = groupedList; 

法比奧解決方案也適用。