user5599599
user5599599

Reputation:

creating a sublist of a list under some condition C#

I want to create a sublist of a list under some condition, but do not know how. Here is an Example:

suppose we have numbers from 1 to 5 and each number has a subarray/array.

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

The numbers that come after : I will save in an array to get access fast.

Now I want to first creat a list of size 5 (numbers 1 to 5) and a sublist for each number under this condition:

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

My desired output would be like this:

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

I could creat the first list by

List<int> List1 = new List<int>();
for (int i = 0; i < 5; i++)
{
    List1.Add(i);
}

but how could I creat the sublist?

Update: I tried

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

but it could not help.

Upvotes: 2

Views: 625

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186803

You can try 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);

Output is

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

Edit: for arbitrary index numbers, I suggest using dictionary with key used as index:

  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());

Upvotes: 1

csharpwinphonexaml
csharpwinphonexaml

Reputation: 3683

Try with this

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]); 
}

From what I understand the input is this

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

And the output should be this:

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

So based on the index items that are smaller or equal to index should be left out

Upvotes: 0

Related Questions