Can you please tell me if it is possible to have a 2D array with two day types. I am new to C#.
For example: array[double][string]
I have radius of flowers alone with their name as follows:
4.7,Iris-setosa
4.6,Iris-setosa
7,Iris-versicolor
6.4,Iris-versicolor
6.9,Iris-versicolor
5.5,Iris-versicolor
6.5,Iris-versicolor
6.3,Iris-virginica
5.8,Iris-virginica
I would like to put these in to a 2D array and sort it according to the first double index. Please let me know if this is possible with an example.
The data that you are trying to organize looks like a list of name-value pairs, with non-unique names. Since the number of items is different for each name, 2D array is not the ideal way to model it. You would be better off with a dictionary that maps names to lists of radii as follows:
Dictionary<string,List<decimal>>
Here is how your data would be organized in such a dictionary:
var data = new Dictionary<string,List<decimal>> {
{"Iris-setosa", new List<decimal> {4.7M, 4.6M}}
, {"Iris-versicolor", new List<decimal> {7M, 6.4M, 6.9M, 5.5M, 6.5M}}
, {"Iris-virginica", new List<decimal> {6.3M, 5.8M}}
};
I am assuming that the representation of the radius needs to be decimal in your case; you could use another representation of real numbers, too, such as float or double.
As comments have said, you likely want a simple class for this:
public class Flower {
public double Radius { get; set; }
public string Name { get; set; }
}
var l = new List<Flower>();
l.Add(new Flower() { Radius = 4.7, Name = "Iris-setosa" });
l.Add(new Flower() { Radius = 4.6, Name = "Iris-setosa" });
/* ... */
Flower[] sorted = l.OrderBy(f => f.Radius).ToArray();
You could get away with an array of KeyValuePair<int, string>, but I don't see much reason to go that route unless you're just looking for something quick and dirty.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With