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個對象,而不是3 – Kenoyer130 2010-10-06 14:54:14
@ Kenoyer130 - 它返回3個對象我。 – Lee 2010-10-06 15:20:29