LINQ query on a list of Object[] arrays
I have a list of Object arrays (List) That I am going to pass into a DLL function to a开发者_运维技巧pply 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)
int textBoxCount = controlsList.Count(o => (int)o[0] == 1);
int checkBoxCount = controlsList.Count(o => (int)o[0] == 2);
// 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();
You can do a GroupBy
followed by a Count
:
var query = controlsList.GroupBy(arr => (int)arr[0])
.Select(g => new { Id = g.Key, Count = g.Count() });
Now query
will contain a list of objects with each identifier and a corresponding count.
I'm a noob at linq, but maybe this will help you ...
var c1 = from t in controlsList
where t[0].ToString() == "1"
select t;
Console.WriteLine("text count = " + c1.Count());
var c2 = from t in controlsList
where t[0].ToString() == "2"
select t;
Console.WriteLine("check count = " + c2.Count());
How about this?
Dictionary<object, int> controls = controlsList.GroupBy(x => x[0]).ToDictionary(x => x.Key, x => x.Count());
int textBoxCount = controls[1];
int checkBoxCount = controls[2];
精彩评论