使用Linq将平面表结果分解为对象集合

时间:2010-10-06 14:43:23

标签: c# 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这只是示例代码,我知道您不应该将List公开为公共属性,而应该返回IEnumerator而不是实际的List等。

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分: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();