请记住,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));
});
});
}