Say i have a list
[1,2,2,1,3,3,3,2,3,3,1,3,3,2,3]

Any ideas how to group them (List<KeyValuePair<int, int>>) so that the key is the next smallest digit, and Value is next biggest digit, and if it repeats itself, group it with the same smallest key, if that makes sense...
This is the output that I am looking for:
[Key, Value]
[0,1]
[0,2]
[3,4]
[3,5]
[3,6]
[7,8]
[7,9]
[10,11]
[10,12]
[13,14]
Based on the image and the example input:
var list = new List<int> { 1, 2, 2, 1, 3, 3, 3, 2, 3, 3, 1, 3, 3, 2, 3}; //example input
var results = new List<KeyValuePair<int, int>>();
int key = 0;
for (int i = 0; i < list.Count; i++)
{
if(i==0 || list[i] < list[i - 1])
key = i++; //assign key and proceed to next index (NB no index out of range checking)
results.Add(new KeyValuePair<int, int>(key, i));
}
This uses a direct comparison with the previous element and uses the indices as key and values as in the example output. If the key value is always smaller than the previous element as in your description, you could replace the if with: if(i==0 || list[i] < list[i - 1])
edit, made the Tuple a KeyValuePair
private static void foo()
{
SortedList<int, List<int>> collection = new SortedList<int, List<int>>();
Random rnd = new Random();
// Filling the collection with random keys/values:
for (int i = 0; i < 100; i++)
{
int key = rnd.Next(0, 10);
if (!collection.ContainsKey(key))
collection.Add(key, new List<int>());
for (int j = 0; j < 10; j++)
{
int value = rnd.Next(0, 1000);
collection[key].Add(value);
}
}
// Displaying all pairs:
foreach (var key in collection.Keys)
{
collection[key].Sort();
for (int j = 0; j < collection[key].Count; j++)
Console.WriteLine(string.Format("[{0},{1}]", key, collection[key][j]));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With