multidimensional Lists<T>?

本文关键字:gt lt Lists multidimensional | 更新日期: 2023-09-27 18:04:39

直到现在我使用多维数组int[,] numbers = new int[3, 2] { {1, 2}, {3, 4}, {5, 6}};,但现在我需要一些动态的东西,如列表。有多维列表这种东西吗?我想创建一个类似于4列表。第四列应该是一个10秒计时器,当10秒过去,特定行的第2列和第3列没有填满时,应从列表中删除整行。

multidimensional Lists<T>?

在。net 4中你可以创建一个元组列表

Try

class Foo{
    public int Col1 { get;set; }
    public int Col2 { get;set; }
    public int Col3 { get;set; }
    public int Col4 { get;set; }
}

List<Foo>

你想要的是List< List< yourtype > >

这将给你你想要的:

List< List<int> > lst = new List< List< int > >;
lst.Add( new List<int>() );
lst[0].Add( 23 );
lst[0][0] == 23;

我建议您创建一个类来封装您所说的列表中单个"行"应该做的事情。它会让你的代码更有表现力,可读性更强,这是任何好代码的核心特征。

最后你会得到List<YourSpecificClass>

这取决于您的应用程序。例如,您可以使用List<List<int>>,并这样添加新项:

myList.Add(new List<int> { 0, 0, 0, 0 });

从你最后的评论听起来,你要对这个列表中的项目应用特定的逻辑,这表明你应该为你的项目创建一个类的可能性,例如

public class Item
{
   public int Col1 { get; set; }
   public int Col2 { get; set; }
   public int Col3 { get; set; }
   public int Col4 { get; set; }
   public bool CanRemove { get { return Col2==0 && Col3 == 0 && Col4 == 0; } }
,然后创建一个List<Item>。然后你可以通过: 删除条目
var toRemove = myList.Where(x => x.CanRemove).ToList();
foreach (Item it in toRemove)
{
   myList.Remove(it);
}

您可以使用包含list的list:

var multiList = new List<List<int>>();
再看一遍你的问题后,我不认为这是你想要的。我猜您想要这样的内容:
public class Item
{
    public int? Col1 { get; set; }
    public int? Col2 { get; set; }
    public int? Col3 { get; set; }
    private Timer Timer { get; set; }
    public List<Item> ParentList { get; set; }
    public Item()
    {
        Timer = new Timer();
        Timer.Callback += TimerCallBack();
        // Set timer timeout
        // start timer
    }
    public void AddToList(List<Item> parentList)
    {
        parentList.Add(this);
        ParentList = parentList;
    }
    public void TimerCallBack() 
    {
        if(!Col3.HasValue || !Col2.HasValue)
        {
            ParentList.Remove(this);
        }
    }
}
....
var list = new List<Item>();
var item = new Item { /*Set your properties */  };
item.AddToList(list);

这应该让你开始。你可以在这里阅读Timer