2010-10-06 50 views
2

我有一個數據庫返回結果,其結果如下所示。我想使用Linq將填充主類項目屬性集合的項目打散到主類中。使用Linq將平坦表結果分解爲對象集合

public class Result 
{ 
public string PrimaryKey { get; set; } 
public string Status { get; set; } 
public string ItemName { get; set; } 
} 

public class ObjectA 
{ 
public string PrimaryKey { get; set; } 
public string Status { get; set; } 

public List<Item> Items = new List<Item>(); 
} 

public class Item 
{ 
public string Name { get; set; } 
} 

static void Main(string[] args) 
{ 
GetObjectAs(); 
} 

static List<ObjectA> GetObjectAs() 
{ 
// this is our table results 
List<Result> results = new List<Result>(); 
results.Add(new Result() 
{ 
    PrimaryKey = "1", 
    Status = "Done", 
    ItemName = "item1" 
}); 
results.Add(new Result() 
{ 
    PrimaryKey = "2", 
    Status = "Fail", 
    ItemName = null 
}); 
results.Add(new Result() 
{ 
    PrimaryKey = "3", 
    Status = "Done", 
    ItemName = "item2" 
}); 
results.Add(new Result() 
{ 
    PrimaryKey = "3", 
    Status = "Done", 
    ItemName = "item3" 
}); 

List<ObjectA> returnResults = new List<ObjectA>(); 

// need to break into 3 ObjectA objects 

// ObjectA 1 needs an Item added to its Items collection with ItemName item1 

// ObjectA 2 has no items since the ItemName above is null 

// ObjectA 3 needs 2 Items added to its Items collection item2 and item3 

// return our collection 
return returnResults; 
} 

PS這只是示例代碼,我知道你不應該讓一個列表作爲公共財產,應該返回一個IEnumerator而不是實際的名單等

回答

4

您可以使用GroupBy到組結果通過主鍵,然後您可以對組中的行的子集進行操作以獲取狀態(希望Status的所有值都相同,這就是爲什麼我使用了First)和項目列表。

var items = results.GroupBy(r => r.PrimaryKey).Select(grp => new ObjectA() 
      { 
       PrimaryKey = grp.Key, 
       Status = grp.Select(r => r.Status).First(), 
       Items = grp.Where(r => r.ItemName != null) 
         .Select(r => new Item() { Name = r.ItemName }).ToList() 
      }).ToList(); 
0
return results 
    .GroupBy(r => r.PrimaryKey) 
    .Select(grp => new ObjectA 
    { 
     PrimaryKey = grp.Key, 
     Status = grp.First().Status, 
     Items = grp.Where(i => i.ItemName != null).Select(i => new Item { Name = i.ItemName }).ToList() 
    }).ToList(); 
+0

這將返回4個對象,而不是3 – Kenoyer130 2010-10-06 14:54:14

+0

@ Kenoyer130 - 它返回3個對象我。 – Lee 2010-10-06 15:20:29

相關問題