Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ query on a list of Object[] arrays

Tags:

c#

linq

I have a list of Object arrays (List) That I am going to pass into a DLL function to apply PDF controls. The first index of each object is supposed to identify what the control will be. I was wondering if there is some way to query my list of objects to get a count of each of the identifying objects and cast it to an int? Here is a example of what i am trying to do ...

        List<Object[]> controlsList = new List<Object[]>();

        //Textfield = 1
        //Checkbox = 2
        Object[] control1 = new Object[] { 1, 1, 1, 75, 75, "txtField1", 1, 8, 10};
        Object[] control2 = new Object[] { 1, 1, 1, 144, 144, "txtField2", 1, 10, 15};
        Object[] control3 = new Object[] { 2, 1, 1, 50, 50, "checkYESNOy", 1, "Yes", "grpYesNo"};
        Object[] control4 = new Object[] { 2, 1, 1, 50, 50, "checkYESNOn", 1, "No", "grpYesNo" };
        Object[] control5 = new Object[] { 2, 1, 1, 50, 50, "checkDirectionN", 1, "North", "grpDirection" };
        Object[] control6 = new Object[] { 2, 1, 1, 50, 50, "checkDirectionS", 1, "South", "grpDirection" };
        Object[] control7 = new Object[] { 2, 1, 1, 50, 50, "checkDirectionW", 1, "West", "grpDirection" };
        Object[] control8 = new Object[] { 2, 1, 1, 50, 50, "checkDirectionE", 1, "East", "grpDirection" };


        controlsList.Add(control1);
        controlsList.Add(control2);
        controlsList.Add(control3);
        controlsList.Add(control4);
        controlsList.Add(control5);
        controlsList.Add(control6);
        controlsList.Add(control7);
        controlsList.Add(control8);

        //Some LINQ code to get back a count of all the textfields(1) and all the checkboxes(2)
like image 717
Spidermain50 Avatar asked Jan 21 '23 15:01

Spidermain50


2 Answers

int textBoxCount = controlsList.Count(o => (int)o[0] == 1);
int checkBoxCount = controlsList.Count(o => (int)o[0] == 2);
like image 168
Kirk Woll Avatar answered Jan 31 '23 02:01

Kirk Woll


// group by first item of each object[]
var groups = controlsList.GroupBy(x => x[0]);

foreach( var g in groups ){
    var count = g.Count();
}

or

var groups = controlsList.GroupBy(x => x[0]).ToList();

var txtCount = groups[0].Count();
var chkCount = groups[1].Count();
like image 29
mathieu Avatar answered Jan 31 '23 02:01

mathieu