請記住,C#可以將自己的對象構建爲容器。這個概念通常被稱爲POCO,或簡單的舊類對象。如果您想要製作更適合特定需求的集合,那麼您可以根據需要進行更新,這將很容易創建這些對象。如果你想保持通用性而不是使用內置插件。代碼應該在.NET 3.5中運行,並在Visual Studio中運行。我在LINQPad中創建了它。如果你想要更具體的功能,我會走這條路線,並且記住你可以隨時改變你的對象。
所以我們來創建兩個容器對象。一個是父母,另一個是該父母的孩子進行示範。在標準的控制檯應用程序中,這些應用程序可能位於「主」入口點之外。然後,我將創建兩種方法來做一些人羣來展示使用POCO作爲容器的要點。
public class JobListing
{
public int Id { get; set;}
public string Name { get; set; }
public List<Job> Jobs { get; set; }
}
public class Job
{
public int Id { get; set; }
public string Name { get; set; }
public string Action { get; set; }
}
public List<Job> CreateJobs()
{
return new List<Job>
{
new Job { Id = 1, Name = "First", Action = "Does It"},
new Job { Id = 2, Name = "Second", Action = "Does It Again"},
new Job { Id = 3, Name = "Third", Action = "Does It Yet Again"}
};
}
public List<JobListing> CreateJobListings()
{
return new List<JobListing>
{
new JobListing { Id = 1, Name = "First Area", Jobs = CreateJobs() },
new JobListing { Id = 2, Name = "Second Area", Jobs = CreateJobs() }
};
}
void Main()
{
// I am just creating a variable that evaluates at runtime to hold my demo data.
var jobslistings = CreateJobListings();
// this is merely an example unboxing the data layer by layer
jobslistings.ForEach(x => {
//x => is a lambda statement and I am using Fluent Syntax off of a method that returns my containers.
//x is now each object in my collection. In this case it is a 'JobListing' object POCO I Made.
Console.WriteLine(string.Format("{0} {1}", x.Id, x.Name));
Console.WriteLine("\tJobs");
x.Jobs.ForEach(y => {
// y => is a lambda statement and I am now in an object of an object.
Console.WriteLine(string.Format("\t\t{0} {1}", y.Id, y.Name));
});
});
Console.WriteLine();
Console.WriteLine("Where Clause");
Console.WriteLine();
// now I am reusing my variable but with a 'predicate' lamba to do a where clause
// this may narrow down my lookups later and I could use a similar example
jobslistings.Where(predicate => predicate.Id == 1).ToList().ForEach(x => {
//x => is a lambda statement and I am using Fluent Syntax off of a method that returns my containers.
//x is now each object in my collection. In this case it is a 'JobListing' object POCO I Made.
Console.WriteLine(string.Format("{0} {1}", x.Id, x.Name));
Console.WriteLine("\tJobs");
x.Jobs.ForEach(y => {
// y => is a lambda statement and I am now in an object of an object.
Console.WriteLine(string.Format("\t\t{0} {1}", y.Id, y.Name));
});
});
}