how to count number of elements in array using LINQ in CSharp Sometimes we need to count number of elements in the array of specific pattern. Here I will show how you can count elements in the array using LINQ in C#.
Suppose we have a list of names in the array and we want to count all the name, then here is the code.
string[] arrNames = new string[]
{
"James",
"Ajay",
"Kisan",
"Adam",
"Adward",
"Jakson",
};
var NameList = from Names in arrNames
select Names;
int NameCount = NameList.Count();
Response.Write(NameCount);
Output
6
If you want to count all the name starts from "A". So here is the code.
string[] arrNames = new string[]
{
"James",
"Ajay",
"Kisan",
"Adam",
"Adward",
"Jakson",
};
var NameList = from Names in arrNames
where Names.StartsWith("A")
select Names;
int NameCount = NameList.Count();
Response.Write(NameCount);
Output
3
If you want to count all the name end with from "n" then here is the code.
string[] arrNames = new string[]
{
"James",
"Ajay",
"Kisan",
"Adam",
"Adward",
"Jakson",
};
var NameList = from Names in arrNames
where Names.EndsWith("A")
select Names;
int NameCount = NameList.Count();
Response.Write(NameCount);
Output
2
Enjoy Coding.........