Trying to read data from the fourth column in c# - unity - c#

I am trying to color some clusters with different colors based on the name assigned to the fourth column of the csv dataset.
this is how the dataset looks like:
0.4601581 0.5122409 0.4826243 Cluster_2
0.4718494 0.4834378 0.4433978 Cluster_3
0.4695727 0.4993355 0.4738764 Cluster_1
I am displaying in unity the first three columns in a cube but want to color the datapoints according to the fourth column.
I have tried this so far:
var cellValue = data.Rows[i][3];
if(cellValue=="Cluster_1")
{
datapointMaterial.SetColor("_Color", new Color(0, 0, 1, 0.2f));
}
and this:
if (!myReader.EndOfStream && hasHeader)
{
string[] header = myReader.ReadLine().Split(separator);
if(header == "Cluster_1")
{
datapointMaterial.SetColor("_Color", new Color(0, 0, 1, 0.2f));
}
else
{
datapointMaterial.SetColor("_Color", new Color(1, 1, 1, 0.4f));
}
}
with this one I get this error:
Cannot implicitly convert type string to string[]
any help would be highly appreciated!

Related

How to find the column count of list of lists in C#?

public static void matrix(List<List<int>> matrix)
{
//matrix.Count is for amount of Row here
}
Example
Here the jagged array is
{{ 1, 2, 3},
{ 4, 5, 6},
{ 7, 8, 9},
{10, 11, 12}}
Then matrix.Count gives 4.
Here I want column count.
If this is array instead of List then I can use matrix.GetLength(0) and matrix.GetLength(1) to find Row count and Column count?
In general case, since you have jagged structure you can define different ColCount:
{
{ 1, 2, 3 }, // Average Columns - 3
{ 4, 5, 6, 7}, // Max Columns - 4
{ 8, 9}, // Min Columns - 2
}
Assuming that null list has 0 columns you can put:
using System.Linq;
...
int minColCount = matrix.Min(list => list?.Count ?? 0);
int maxColCount = matrix.Max(list => list?.Count ?? 0);
int avgColCount = (int)Math.Round(matrix.Average(list => list?.Count ?? 0));
If you can guarantee that matrix is rectangular and doesn't contain null, you can put
int colCount = matrix.Count > 0 ? matrix[0].Count : 0;
You are using a list of list of int. In this situation, there is no guaranty that you have a matrix with fix column size.
For example { {1}, {4,5,6}, {7,8}, {10,11,12,13} } is a possible combination.
But, if you are sure inside lists have the same size you can get the first list's size.
int column = matrix?.FirstOrDefault()?.Count ?? -1;
Don't forget to add using System.Linq; at top of your code.

Issue while sorting Combo Box

I'm working on a task in which I need to populate the comboBox through List and the List is populating from employee.dat file. I'm successfully populates the combo but while sorting it I'm facing an issue. The Values which I'm trying to sort is String Numbers. It shows the values from 0-9 but when it beyond from 9 the combo looks goofy.
Here is the screenshot
What I need to do is sort these values, Means 10 should be leading by 9.
Here is the code snippet which I have tried yet.
private void FormDelete_Load(object sender, EventArgs e)
{
//LOAD EVENT for FORM
//Clear all form controls
Reset();
//Fill the ID Combo box using data in List<T>
comboBoxID.Items.Clear();
foreach (MyClass.Employee obj in MyClass.listEmployees)
{
comboBoxID.Items.Add(obj.ID);
}
//Sort the combo box ibn ascending order
comboBoxID.Sorted = true;
}
Employee.cs
public class Employee
{
public int ID;
public string fName;
public string lName;
public string gender;
public int age;
public double hourWage;
}
public static List<Employee> listEmployees = new List<Employee>();
Empolyee.dat
1, Ann, Crowe, F, 34, 12.95
2, Bob, Costas Jr., M, 27, 8.75
3, Sue, Soppala, F, 22, 7.95
4, Bill, Barton, M, 45, 15.25
5, Jill, Jordan, F, 33, 14.75
6, Art, Ayers, M, 33, 14.75
7, Larry, Stooge, M, 55, 21.05
8, Art, Ayers, M, 33, 14.75
9, Larry, Stooge, M, 55, 21.05
10, Art, Ayers, M, 33, 14.75
11, Larry, Stooge, M, 55, 21.05
List Populating code
if (File.Exists("employee.data"))
{
try
{
streamEmployee = new StreamReader("employee.data");
string line; //to read a line from the text file
string[] arrFields = new string[5];
while (streamEmployee.Peek() > -1)
{
line = streamEmployee.ReadLine(); //read a line of records from file
arrFields = line.Split(','); //split the line at comma junction, and save split //fields in array
MyClass.Employee objEmp = new MyClass.Employee(); //create a "specific" employee //object instance
//Assign each field from line as generic object's properties to make it "specific
objEmp.ID = Convert.ToInt32(arrFields[0].Trim()); //ID is integer
objEmp.fName = arrFields[1].Trim();
objEmp.lName = arrFields[2].Trim();
objEmp.gender = arrFields[3].Trim();
objEmp.age = Convert.ToInt32(arrFields[4].Trim()); //age is integer
objEmp.hourWage = Convert.ToDouble(arrFields[5].Trim()); //hourly wage is double
//Add this specific employee object to the List
MyClass.listEmployees.Add(objEmp);
} //while
} //try
catch (IOException err)
{
MessageBox.Show(err.Message);
error = true;
} //catch
finally
{
if (streamEmployee != null) //it is indeed representing a file and may not be closed
streamEmployee.Close();
} //finally
} //if
Your file is already sorted, thus there is no need to call Sorted=true.
Anyway, if you want to be sure that, whatever order is present in the input file, your code adds the employees following the ID order, then you could change your loop to
foreach (MyClass.Employee obj in MyClass.listEmployees.OrderBy(x => x.ID))
{
comboBoxID.Items.Add(obj.ID);
}
Again no need to set the Sorted property to true....

DotNetHighCharts Pie Chart Labels Show Slice

I am using DotNetHighCharts and playing around with the various chart formats. The Pie Chart labels show “Slice” for each slice of the pie. What parameter is used to change this to the actual name of the slice?
I got this figured out. I was using the PlotOptions like this
.SetPlotOptions(new PlotOptions
{
Pie = new PlotOptionsPie
{
DataLabels = new PlotOptionsPieDataLabels
{
Formatter = "function() { return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %'; }"
}
}
})
However, I wasn’t passing in the names of the datapoint. So I created a namesAndVals object array that was passed into the Data element of the .SetSeries method.
object[] names = new object[] { “Val1", “Val2", “Val3", “Val4" };
object[] vals = new object[] { 11, 12, 13, 14 };
object[,] namesAndVals = new object[4,2];
for (int i = 0; i < names.Count(); i++)
{
namesAndVals[i, 0] = names[i];
namesAndVals[i, 1] = vals[i];
}
If there is a better way to create the final array I’m open to suggestions. Eventually, the gals and names will be driven by a database.

Converting a string to an equation with variables

My program currently loads a csv file and converts each line to different strings and int values. The problem is, while I can easily convert a simple number, it needs to be able to convert an equation with variables.
My current code for this is -
string[] values = line.Split(new string[] { "," }, StringSplitOptions.None)
.Select(p => p.Trim()).ToArray();
if (values.Length != 8) continue;
var species = new SpeciesClasses()
{
Species = values[0],
Description= values[1],
Strength = int.Parse(values[2]),
Intelligence = int.Parse(values[3]),
Dexerity = int.Parse(values[4]),
Charisma = int.Parse(values[5]),
Endurance = int.Parse(values[6]),
Initiative = int.Parse(values[7]),
};
And my csv file is
Pilot, Trained to handle all vehicle types., 0, 6, 0, 0, 0, 0
Medic, Trained to cure and heal others., 0, 0, 5, 0, 0, 0
Which works fine, now the tricky part is a line like this -
Berzerker, The closer to death this crew gets - the stronger they hit., (15-HP)/4, 0, 0, 0, 0, 0
Focused, Using their mass intellect - this crew can aim more accurately., 0, 0, INTEL, 0, 0, 0
So I not only need to convert the string to an int equation with different variables - in this case an HP and INTEL int.
If int.Parse() fails (btw try int.TryParse(...)) fallback to a more specialized tool:
More info here:
Equation (expression) parser with precedence?

Address custom enum values by order

Usually I can address each item in an enum by it's ordered position (0, 1, 2, 3...), but if I've created an enum with custom values (as below), is there still a way to address each item by its declared order (e.g., Off = 0, _5m = 1, _15m = 2, etc.), rather than its value?
enum WaitTime { Off = 0, _5m = 5, _15m = 15, _30m = 30, _1h = 60, _2h = 120, _3h = 180, _6h = 360, _12h = 720, _1d = 1440, _2d = 2880 }
In C# You can use Enum.GetValues() method.
It retrieves an array of the values of the constants in a specified
enumeration. The elements of the array are sorted by the binary values
of the enumeration constants.
Array enumElementsInArray = Enum.GetValues(typeof(WaitTime));
int firstElement = enumElementsInArray[0];
int secondElement = enumElementsInArray[1];
But know that, it will return the aray after sorting elements by their values. But of course, for your enum it will work as you want.
This would be a generic way that works for all types of enums:
public static T GetValueAt<T>(int idx)
{
var vals = Enum.GetValues(typeof(T));
return (T)vals.GetValue(idx);
}
Usage:
var value = GetValueAt<WaitTime>(2); //returns _15m
(Answer for C#)
No you wont, e.g. _5m converts to 5, not to 1.
What you call "order" is an implicit conversion to an integer (which by default is 0 ... N-1 for an enum with N values)
enum WaitTime { Off = 0, _5m = 5, _15m = 15, _30m = 30, _1h = 60, _2h = 120, _3h = 180, _6h = 360, _12h = 720, _1d = 1440, _2d = 2880 }
class Program
{
static void Main()
{
WaitTime wt = WaitTime._15m;
Console.WriteLine((int)wt);
}
}
Will output 15.
PS.: avoid leading underscores when declaring your enum values.

Categories

Resources