我是C#的新手并且已经阅读了C#编程的入门书籍,但我仍然不确定设置类的3D数组的最佳方法。这是一个小背景:
我需要在堆栈中跟踪类的实例,称为容器。将需要跟踪m个n个堆栈,因此需要跟踪3d数组。将在堆栈中添加和删除容器。我将需要搜索所有容器以找到符合某些条件的容器。将选择其中一个容器;该容器及该特定堆栈中它上面的所有容器都需要移动到另一个堆栈。
我认为使用LINQ查询将是搜索所有容器的最佳方式,这意味着我应该使用某种类型的集合(如List)来容纳所有容器。我见过的所有收藏品似乎只有一个索引器,这让我觉得我可以使用List并自己跟踪3D索引。
采取什么方法?
答案 0 :(得分:0)
你可以使用/管理这些,而不是C#代码中的3d数组!
var d3Stack = new Stack<Stack<Stack<MyJob>>>();
var d3List = new List<List<List<MyJob>>>();
答案 1 :(得分:0)
请记住使用C#,您可以将自己的对象构建为容器。该概念通常被称为POCO或普通旧类对象。如果您想要根据特定需求量身定制的集合可以根据需要进行更新,那么创建这些对象会很容易。如果你想保持它的通用性而不是使用内置的ins。代码应该在.NET 3.5及更高版本的Visual Studio中运行。我在LINQPad中创建了它。如果您想要更具体的功能,我会选择这条路线,请记住,您以后可以随时更改对象。
因此,让我们创建两个容器对象。一个是父母,另一个是父母的孩子,用于示范。在标准的控制台应用程序中,这些应用程序可能位于&#39; Main&#39;之外。入口点。然后我将创建两种方法来进行一些填充,以证明使用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));
});
});
}