Use count of each Series intance as Y values - c#

This is the code I have so far, basically it's getting the actual value of uniqueid and using that as the value for each series:
string[] XPointMember = new string[table.Rows.Count];
int[] YPointMember = new int[table.Rows.Count];
for (int count = 0; count < table.Rows.Count; count++)
{
XPointMember[count] = table.Rows[count]["GuitarBrand"].ToString();
YPointMember[count] = Convert.ToInt32(table.Rows[count]["UniqueID"]);
}
//binding chart control
chart1.Series[0].Points.DataBindXY(XPointMember, YPointMember);
What I'm trying to accomplish is adding the count of each instance of that guitar brand to show as the value. So if there are 4 instances of a particular GuitarBrand than the value should be 4.
Thanks!

This should do it:
//First populate the X axis only (the series)
for (int index = 0; index < table.Rows.Count; index++)
{
XPointMember[index] = table.Rows[index]["GuitarBrand"].ToString();
}
//Loop again, and for each series, use the Count method
//to see how much occurrences of the same guitar brand are there
for (int index = 0; index < table.Rows.Count; index++)
{
var guitar_brand = XPointMember[index];
YPointMember[index] = XPointMember.Count(x => x == guitar_brand);
}
Please note that I used index instead of count for the loop variable. Using count here makes it confusing for the reader of the code.

Related

Quickest way to assign each value of list to a value of another list

If say, we have a list with serial numbers and another list with products, which is the quickest (and more elegant) way to assign one serial number to each product?
Can use the classic:
var serialNumbers = CreateSerialNumbers().ToList();
var index = 0;
foreach (var product in Products)
{
product.SerialNumber = serialNumbers[index];
index++;
}
or for
for (int index= 0; index < Products.Count; index++)
{
Products[index].SerialNumber = serialNumbers[index];
}
but are there quicker/more elegant ways? Maybe with Linq?
I would do this:
for (int index= 0; index < Products.Count; index++)
{
Products[index].SerialNumber = serialNumbers[index];
}
...but you need to make sure serialNumbers[index] is not out of bounds as well. Maybe...
for (int index= 0; index < Products.Count; index++)
{
if(serialNumbers.Count >= index
Products[index].SerialNumber = serialNumbers[index];
else
index = Products.Count;
}
That isn't really the safest thing to do, but it will work here.

Save the sum of each row of a matrix into an array

I have a matrix and I want to return an array containing as elements the sum of each row elements of the matrix.
int [] sum;
for (var i = 0; i < m; i++)
{
for (var j = 0; j < result.Pages[i].Actual.Count; j++)
{
sum[i] += result.Pages[i].Actual[j];
}
}
This is how I tried to do it but seems it is not working. Any ideas?
Use var m = a.GetLength(0); to get number of rows, and var n = a.GetLength(1); to get number of columns.
now that looks like a different story after you edit:
Actually the first problem would be a NullreferenceException because int[]sum is not initialized!
Anyway, so it seems that you have an array of arrays. In this case you would need the Length of the Pages array to save your results. The first loop iterates over it using i and will run until result.Pages.Length. For each i you have correctly implemented a second loop where you sum up the result.
int [] sum = new int[result.Pages.Length];
for (var i = 0; i < result.Pages.Length; i++)
{
for (var j = 0; j < result.Pages[i].Actual.Length; j++)
{
sum[i] += result.Pages[i].Actual[j];
}
}
If you collections are List's then you need to use Count instead of Length
The Linq solution would look like this:
int [] sum = result.Pages.Select(x=>x.Sum()).ToArray();
EDIT:
double? means that you have a nullable data type. This is different from the normal double. Furthermore the default value will be null That means that you need to initialize the value at position i in sum before you add up values, otherwise the result will be null.
double? [] sum = new double?[result.Pages.Length];
for (var i = 0; i < result.Pages.Length; i++)
{
sum[i] = 0;
for (var j = 0; j < result.Pages[i].Actual.Length; j++)
{
sum[i] += result.Pages[i].Actual[j];
}
}

Storing cookie in string array variable and displaying the string

I am trying to store the cookie in an array of string and splitting it .when i try to display the array i am getting index out of bound error in the for loop.
Please not the the value of "cboColumn.getSelectedValues()" is a list of selected columns from a grid which is in format"column1,column2,column3......columnn"
Response.Cookies["Column"].Value = cboColumn.getSelectedValues();
String items = Request.Cookies["Column"].Value;
String[] item = items.Split(',');
Response.Write(items);
Response.Write(item[0]);
for (int i = 0; i <= item.Length; i++)
{
Response.Write(item[i]);
}
Change your for loop like this:-
for (int i = 0; i <= item.Length - 1; i++)
{
Response.Write(item[i]);
}
Or as suggested by #BillK, you can simply change the condition like this:-
for (int i = 0; i < item.Length ; i++)
Array is zero index based so it will range from 0 to (n-1) but you are trying to fetch value from 0 to n, which is causing this issue.

How can I start initialization of "List of list" with columns

I have a list of list and I want to add values column oriented. Like in the following code sample:
Data = new List<List<double>>();
for (int i = 0; i < columnCount; i++)
{
for (int j = 0; j < rowCount; j++)
{
Data[j][i] = (probabilityList[j]) * K); // It won't work
}
}
I know it won't work because Data's index does not exist at current situation, and I need to use add() method.
However, I need to add values to list starts with columns:
[1 , null] ----> [1, null]
[null, null] [2, null]
How can I add values to a list of list starts with columns?
You need to create actual lists that you place inside your outer list of lists:
for (int i = 0; i < rowCount; i++)
{
Data.Add(new List<double>());
}
Once you've created all of the inner lists you can go through them and add values to them:
for (int i = 0; i < columnCount; i++)
{
for (int j = 0; j < rowCount; j++)
{
Data[j].Add((probabilityList[j]) * K);
}
}
Since you know the number of columns and rows you need you might think about using arrays instead of lists. When an array is initialized all members of the array are initialized to their default values. This would make your code
double[,] Data = new double[columnCount,rowCount];
for (int i = 0; i < columnCount - 1; i++)
{
for (int j = 0; j < rowCount - 1; j++)
{
Data[j,i] = (probabilityList[j]) * K);
}
}
You'll need to new up each element of the List of Lists
Data = new List<List<double>>();
for (int i = 0; i < columnCount; i++)
{
List<double> column = new List<double>();
for (int j = 0; j < rowCount; j++)
{
//not really sure if this is the correct code here
//that would depend on your logic
column.Add((probabilityList[j]) * K);
}
Data.Add(column);
}
A list is not an array. It does not have slots that you just put elements in, it's more like a chain.
So initially you have a List<List<double>> that is empty, it has no List<double> instances in it. You have to (explicitly) create and add those lists to the Data list.
Alternatively, if you do need row and columns with slots for elements, you could use a two-dimensional matrix, like this:
var matrixData = new double[rowCount, columnCount];
for (int i = 0; i < columnCount; i++)
{
for (int j = 0; j < rowCount; j++)
{
matrixData[j, i] = ((probabilityList[j]) * K);
}
}
A popular way to initialize a list of lists (List<List<T>>) with one line of code is to use LINQ as follows:
List<List<double>> Data = Enumerable.Range(0, columnCount).Select(i => new List<double>()).ToList();
This will produce a list of empty initialized lists of double type. From here every inner list can be accessed as Data[i] and elements can be added to it as Data[i].Add(double).
Here is a breakdown of what LINQ methods do to initialize a List<List<double> >
Enumerable.Range(0, columnCount)
Returns IEnumerable collection of Int with the columnCount number of members.
.Select(i => new List<double>())
For each of the element of the collection returned by the previous step runs a function "new List()" and stores output (initialized empty List of double) in IEnumerable collection (so we get IEnumerable<List<double>> with columnCount number of members).
.ToList();
Converts the collection in the step above IEnumerable<List<double>> to List<List<double> - the desired output.
In short: You have to initialize each collection of List<T> inside of your parent List<T> collection.
As you may know, initialization of collections is done throw keyword new in .NET Framework. Otherwise, all inner Lists will be Null and you would not be able to access them.
I have applied this concept to your code.
var mainData = new List<List<double>>();
for (int i = 0; i < columnCount; i++)
{
var innerList = new List<double>();
for (int j = 0; j < rowCount; j++)
{
innerList.Add((probabilityList[j]) * K);
}
mainData.Add(innerList);
}

Checking the size of a list of arrays

I have a list of string arrays:
List<string[]> parsedRaw = new List<string[]>();
This list contains lines read in from a CSV, where parsedRaw[3][5] would be the fifth item read off the third line of the CSV.
I know that I can find the number of rows in the list with:
parsedRaw.Count
But, given a row, how can I find the number of elements in that row? I'm trying to implement a test before entering a loop to read from the list, in order to avoid an "Index was outside the bounds of the array" error, where the loop is:
for (k = 0; k < nBytes; k++)
{
TheseBytes[k] = (byte)parsedRaw[i][StartInt + k];
}
I'm encountering the error on a row in the CSV that has fewer elements than the others. Before entering this loop, I need to check whether parsedRaw[i] has at least "StartInt + nBytes" elements.
Thanks for any suggestions!
A row is just a string array string[], so you can find its size using the Length property of the array.
foreach (string[] row in parsedRaw) {
for (int i = 0 ; i != row.Length ; i++) {
// do something with row[i]
}
}
The number of elements in a given row is determined by
parsedRaw[theRowIndex].Length
To fix your for loop you need to constrain the StartInt + k value to be less than the minimum of nBytes and the row length
for (k = 0; (k < nBytes) && (k + StartInt < parsedRaw[i].Length); k++)
{
TheseBytes[k] = (byte)parsedRaw[i][StartInt + k];
}
Try
List<string[]> parsedRaw = new List<string[]>();
parsedRaw.Add(new string[] {"test1", "test2"});
parsedRaw.Add(new string[] { "test1", "test2", "test3" });
int totalSize = 0;
for (int i = 0; i < parsedRaw.Count(); i++)
{
int rowSize = 0;
for (int k = 0; k < parsedRaw[i].Count(); k++)
{
rowSize += parsedRaw[i][k].Length;
}
totalSize += rowSize;
}

Categories

Resources