I have a database return result which has flatten results like below. I want to use Linq to break the flat results into primary classes with the items populating the primary class items property collection.
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 this is just sample code, I know you shouldn't expose a List as a public property and should return an IEnumerator instead of the actual List etc.