在某些条件下创建列表的子列表C#

时间:2015-12-08 09:38:41

标签: c# list

我想在某种条件下创建列表的子列表,但不知道如何。这是一个例子:

假设我们有1到5的数字,每个数字都有一个子数组/数组。

1: 1 5 7 5 5 3 4 9
2: 0 1 2 3 4 6 3 4
3: 9 4 6 7 0 0 3 1
4: 4 6 3 7 8 0 0 1
5: 8 0 3 1 0 2 4 6

:之后的数字我将保存在一个数组中以便快速访问。

现在我想在这种情况下首先创建一个大小为5的数字列表(数字1到5)和每个数字的子列表:

if(list[i] > (arr1[j] + 1))
{
   //then save it in a sublist of the index i
}

我想要的输出是这样的:

List
    [1]
       [5]
       [7]
       [5]
       [5]
       [2]
       [4]
       [9]
    [2]
       [4]
       [6]
       [4]
    .
    .
    .
    [5]
       [8]

我可以通过

创建第一个列表
List<int> List1 = new List<int>();
for (int i = 0; i < 5; i++)
{
    List1.Add(i);
}

但我怎么能创建子列表?

更新:我试过了

List<Tuple <int,int>> List1 = new List<Tuple <int,int>>();

但它无能为力。

2 个答案:

答案 0 :(得分:1)

您可以尝试 Linq

  List<int[]> source = new List<int[]>() {
    new int[] { 1, 5, 7, 5, 5, 3, 4, 9},
    new int[] {0, 1, 2, 3, 4, 6, 3, 4},
    new int[] {9, 4, 6, 7, 0, 0, 3, 1},
    new int[] {4, 6, 3, 7, 8, 0, 0, 1},
    new int[] {8, 0, 3, 1, 0, 2, 4, 6},
  };

  var result = source
    .Select((array, index) => array
      .Where(item => item > index + 2) // +2 since index is zero-based
      .ToArray()); // ToArray is not necessary here, but convenient for further work

  // Test

  String report = String.Join(Environment.NewLine, 
    result.Select(item => String.Join(", ", item)));

  Console.Write(report);

输出

   5, 7, 5, 5, 3, 4, 9
   4, 6, 4
   9, 6, 7
   6, 7, 8
   8

编辑:对于任意索引号,我建议使用词典,并将键用作索引:

  Dictionary<int, int[]> source = new Dictionary<int, int[]>() {
    {1, new int[] { 1, 5, 7, 5, 5, 3, 4, 9}},
    {2, new int[] { 0, 1, 2, 3, 4, 6, 3, 4}},
    {3, new int[] { 9, 4, 6, 7, 0, 0, 3, 1}},
    {4, new int[] { 4, 6, 3, 7, 8, 0, 0, 1}},
    {5, new int[] { 8, 0, 3, 1, 0, 2, 4, 6}},
  };

  var result = source
    .Select(pair => pair.Value
       .Where(item => item > pair.Key + 1)
       .ToArray());

答案 1 :(得分:0)

试试这个

List<Tuple <int,List<int>>> list = new List<Tuple <int,List<int>>>();

//populate the list 

if(list[i].Item1 > (arr1[j] + 1))
{
    list[i].Item2.Add(arr1[j]); 
}

据我所知,输入是

1: 1 5 7 5 5 3 4 9
2: 0 1 2 3 4 6 3 4
3: 9 4 6 7 0 0 3 1
4: 4 6 3 7 8 0 0 1
5: 8 0 3 1 0 2 4 6

输出应为:

1: 5 7 5 5 3 4 9
2: 4 6 4
3: 9 6 7
4: 6 7 8
5: 8

因此,基于索引的项目应小于或等于索引