Reputation: 2250
I'm trying to sort a list containing bool 2D arrays like below.
List<bool[,]>boolList;
bool[,] bool2DArray = {
{true,true,true,true},
{true,true,true,true},
{true,true,true,true}
};
I've been trying to sort the list they're in by the amount of true counts within each 2D Array.
After some research and looking over Stack Overflow I haven't been able to find a solution for this specific issue; many of the solutions I was able to find wouldn't work for me in this situation where I'm not comparing them directly, but rather the result of a calculation on them which led me to trying with a Lambada type solution which also failed but I think that might have been due to me not understanding how to implement it correctly.
Simple function I made for getting the count
int GetCount(bool[,]bool2DArray) {
int count = 0;
int rows = bool2DArray.GetUpperBound(0);
int columns = bool2DArray.GetUpperBound(1);
for (int x = 0; x <= rows; x++) {
for (int i = 0; i <= columns; i++) {
bool isTrue = bool2DArray[x, i];
if (isTrue) {
count++;
}
}
}
return count;
}
And this is the Lambada type solution I think is in the right direction but isn't valid.
List<bool[,]> sortedList = boolList.Sort((a,b) => (GetCount(a).CompareTo(GetCount(b))));
Upvotes: 1
Views: 107
Reputation: 5203
I prefer this approach which I think is more readable and cover more usecases:
class Program
{
static void Main(string[] args)
{
List<bool[,]> boolList = new List<bool[,]>() {
new bool[,] {
{true,true,true,true},
{true,true,true,true},
{true,true,true,true}
},
new bool[,] {
{false,true,true,true},
{false,true,true,true},
{false,true,true,true}
}
};
boolList = OrderBoolArraysByBoolean(boolList, true);
}
private static List<bool[,]> OrderBoolArraysByBoolean(List<bool[,]> listOfArrays, bool value)
{
return listOfArrays.OrderByDescending(x => x.Cast<bool>().Count(i => i == value)).ToList();
}
}
Upvotes: 0
Reputation: 37299
You'd first want to see how to easily work with the 2d array and count the number of true
s in it. To do so for a single item, you could do something similar to what is found in this question: Fast way to convert a two dimensional array to a List ( one dimensional )
bool2DArray.Cast<bool>().Count(i => i)
Then wrapping that with OrderDescendingBy
you get the desired result:
var collection = new List<bool[,]> { bool2DArray, ... };
var result = collection.OrderByDescending(item => item.Cast<bool>().Count(i => i));
Upvotes: 2