C# How to add elements to a specific index? - c#

I have a Class like this:
internal class Name
{
public decimal A { get; set; }
public decimal B { get; set; }
}
internal class Type
{
public string FullyName { get; set; }
public List<Name> Name{ get; set; }
public Type()
{
Name = new List<Name>();
}
}
I can add new Elements to List like this:
internal static List<Type> test = new List<Type>();
var pl = new Type{ Name = "test" };
pl.Name.Add(new Name { A = 0, B = 1 });
test.Add(pl);
But how can I add only new Decimals ("under Name") at a specific index and not to new rows at FullyName? So I want new rows under Names and not new rows under FullyName
I tryed with this, but it is not working
test.Insert(index, 0, 1);
I mean this: (adding new items/elements under "Name" in a specific index FullyName: XY Collection)
FullyName: XY
[0] > Name:
[0] > decimal A: 0
[1] > decimal B: 1
[2]... and so on
FullyName: ZA
[1] > Name:
[0] > decimal A: 0
[1] > decimal B: 1
[2] > decimal A: 3
[3] > decimal B: 4
[4]... and so on
-So, if i Search with Linq the Index of the FullyName XY the Answer is 0: So then i must add new Items/Elements (decimal A / decimal b) under FullyName: XY with the Index of 0 (then under Name adding new Items/Elements), but this is not working with my code for adding new FullyNames or Insert :/
-Hope now is Clearly what i mean :)
thx

First, you need to find the index of which FullyName list you want to add decimals to. You seem to be able to do this with LINQ already. Let's say you store this index in a variable called index.
Now, test[index] will give you a Type object, so test[index].Name will give you a List<Name>, which you can add, insert, remove (or do whatever) pairs of decimals (they're actually Name objects).
To add { A = 0, B = 0 } at to the FullyName list at index index, you do:
test[index].Name.Add(new Name { A = 0, B = 0 });
I think your confusion comes from the naming of your members. You should definitely give better names to them. Maybe:
internal class DecimalPair
{
public decimal A { get; set; }
public decimal B { get; set; }
}
internal class DecimalPairs
{
public string FullName { get; set; }
public List<DecimalPair> Decimals{ get; set; }
}

Related

get specific properties within the generic list using linq

I have generic list foo as shown below
var foo = new List<XYZ>();
public class XYZ
{
public String TimeZone { get; set; }
public Decimal? B1Volume { get; set; }
public Decimal? B2Volume { get; set; }
public Decimal? B3Volume { get; set; }
public Decimal? B4Volume { get; set; }
public Decimal? B5Volume { get; set; }
// .............
// .............
public Decimal? B24Volume { get; set; }
public String Name {get;set;}
}
how do I select the properties B1Volume,........B24Volume ?
I tried with following code mentioned below, but it's not giving expected results
var hp = foo.Skip(1).Take(23).ToList();
There's a few ways, but I do not think that you want to go down that road.
Do you really want a list of xyz? Or asked in a different fashion: Do you have many different lists of lists of volumes? Or do you only want to express a single list of volumes?
Maybe what you want to do is declare an array inside XYZ like this
public class XYZ
{
public String TimeZone { get; set; }
public Decimal?[] Volumes {get; set;} = new Decimal?[24];
public String Name {get; set;}
}
If you want to access volumes by an index (1,2,...,24) you need an array or any other kind of indexed data structure.
Then you could do
var xyz = new XYZ();
xyz.Volumes[0] = 12.0;
xyz.Volumes[1] = 23.0;
.....
and basically access the volumes by xyz.Volumes and adding an index to get the n-th volume
If you now want to further list these XYZ you could do something like this:
var listOfXyz = new List<XYZ>();
listOfXyz.Add(new XYZ());
....
listOfXyz[3].Volumes
this would give you the 24 volumes of the element at the index of 3 in the list.
You need to do a Select:
var hp = foo.Select(x => new { x.BVolume1, x.BVolume2, ..., x.BVolume24 });
Although I do agree with #Himzo that this is not the best way to solve your problem if you can change the structure.
Maybe it helps:
XYZ xyz = new XYZ();
Type t = xyz.GetType();
List<PropertyInfo> properties = new List<PropertyInfo>(t.GetProperties());
var hp = properties.Skip(1).Take(23).ToList();
Do not forget adding name space:
using System.Reflection;
Update
In comments GBreen12 suggests to add a filter for getting only properties that has name containing volume. Now if you add another properties the code will not fail. So you can change the 3th line to this:
List<PropertyInfo> properties = (new List<PropertyInfo>(t.GetProperties())).Where(x => x.Name.EndsWith("Volume")).ToList();
Now you do not need last line var hp = ... and the properties is your answer.

an array list with n rows and four columns in c#

I need a clear example that shows me how to define a list that has n rows and 4 columns and how to use it. I need a list to save my data like the below image. as you see this could be a dictionary.
You need to create a class with all the above properties
public class Sample
{
public string vocabulary { get; set; }
public string meaning { get; set; }
public int number { get; set; }
public int group { get; set; }
}
and then you can create a List of type Sample,
List<Sample> yourList = new List<Sample>();
You can add items to the list as below
yourList.Add(new Sample { vocabulary = "massive", meaning = "very big", number = 5, group = 15 });
You can access them later like this, if you want the first element,
var result = yourList[0];
this is the easiest and best way of doing it. You need to create a new class and then create new instances of the class and then add it to the list and then use LINQ to get the data out
void Main()
{
var list = new List<myClass>()
list.Add(new myClass() {
Vocabluary = "Vocabluary ",
Meaning = "meaning",
Number = 1,
Group = 2})
}
public class myClass
{
public string Vocabluary { get; set; }
public string Meaning { get; set; }
public int Number { get; set; }
public int Group { get; set; }
}
yes... as Sajeetharan mentioned, with a custom class you can create an any dimensions List. but i don't think you need to think about dimension in C#... it is a bit more high level than that.
just simply create a class and put everything you need in it...
public class CustomClass{
public string d1;
public int d2;
public string d3;
public string d4;
...
//you can easily create a N dimension class
}
to access it and apply it
public void Main(){
List<CustomClass> list = new List<CustomClass>();
CustomClass cc = new CustomClass();
cc.d1 = "v1";
cc.d2 = 0; //v2
list.Add(cc);
//to access it
foreach(CustomClass tmpClass in list)
{
string d1Value = tmpClass.d1;
int d2Value = tmpClass.d2;
}
}

Array of arrays with string keys in c#

I am new to C# but i have a background in PHP. Working some basic stuff in C# i came across some odd thing for me. I want to create an array of arrays in C# with string keys that hold another array of string keys. If I had to do this in PHP it whould look like this:
$workers = array("John" => array("salary" => 1000, "bonus" => 200),
"Michal" => array("salary" => 1500, "bonus" => 0)
);
Digging into C# I found some answers like hashtable or dictionary, but it made me more confused.
C# is not like PHP in that it is not loose so you need to declare exactly what the array (hashtable if you want string keys) can hold. Meaning if you wish to have an array of arrays, then the parent array needs to be told that it holds arrays and cannot hold anything else.
This has basicly been answered here:
How to initialize a dictionary containing lists of dictionaries?
Arrays in .NET doesn't have key-value pairs, so you would need to use a different collection for that, like a dictionary.
The closest to your PHP code would be a dictionary of dictionaries, however a dictionary of custom classes work be more in line with how data is handled in C#.
The class:
public class Worker {
public int Salary { get; set; }
public int Bonus { get; set; }
}
The dictionary:
Dictionary<string, Worker> workers = new Dictionary<string, Worker>();
workers.Add("John", new Worker{ Salary = 1000, Bonus = 200 });
workers.Add("Michal", new Worker{ Salary = 1500, Bonus = 0 });
This allows you to locate a worker by name, and then access the properties. Example:
string name = "John";
Worker w = workers[name];
int salary = w.Salary;
int bonus = w.Bonus;
Create a class for your object Worker:
public class Worker
{
public string Name { get; set; }
public double Salary { get; set; }
public int Bonus { get; set; }
public Worker(string name, double salary, int bonus)
{
this.Name = name;
this.Salary = salary;
this.Bonus = bonus;
}
}
Then create a List of workers:
List<Worker> workers = new List<Worker>() {
new Worker("John", 1000, 200),
new Worker("Michal", 1500, 0)
};
What you can do in c# is something like this :
public class Employee
{
public string Name { get; set; }
public double Salary { get; set; }
public int Bonus { get; set; }
public Employee(string name, double salary, int bonus)
{
this.Name = name;
this.Bonus = bonus;
this.Salary = salary;
}
}
And create dictionary :
Dictionary<string, Employee> emps = new Dictionary<string, Employee>();
emps.Add("Michal", new Employee("Michal", 1500, 0));
emps.Add("John", new Employee("John", 1000, 200));
Or sometimes you may wish to use dynamic and anonymous type for our employees rather then strong type (such as Employee) :
var John = new { Salary = 1000, Bonus = 200 };
var Michal = new { Salary = 1500, Bonus = 0 };
var dict = new Dictionary<string, dynamic>()
{
{"John", John},
{"Michal", Michal},
};
Console.WriteLine(dict["John"].Bonus);
output : 200

Organizing data with 3 arrays in C#

I am making a program that automates data messaging.
I have an Excel sheet that has a Name column, Type Column, and Value Column.
It looks like this:
Name Type Value
Sam A 32
Ben B 65
Sam B 213
max B 23
max C 24
max C 12
Ben C 45
This data is not real, but it is similar to what I am working with.
Note: some of the names do not have certain types.
I have loaded the data in 3 arrays arrName[], arrType[], and arrValue[]
I wish to make the data look like this with a 3D array arrPro[name, type, value]. All the values of the same type should belong to the same name and all the values should be added up together to form a total value.
Load excel data directly to DataSet is the most simple method.
If you do want a 3D array, I suggest
Tuple<string, string, int> as the data holder for each row.
and
List<Tuple<string, string, int>> will hold all your data.
This structure might hold your data
public class MyTypes
{
public string TypeName;
public List<NamesValues> Names;
}
public class NamesValues
{
public string Name;
public List<int> Values;
}
It's not simplier and cleaner to store your data in some List<YourObject> for example:
public class YourObject {
public string Name { get; set; }
public string Type{ get; set; }
public int Value { get; set; }
}
and then count what you want with linq (more less):
List<YourObject> yourObject = "your logic goes here (with whole data)";
List<YourObject> result = from s in yourObject
group s by new { s.Name, s. Type) into r
select new YourObject { Name = r.Name, Type = r.Type, Value = r.Sum(s => s.Value) };
I'm not shure it's exactly what you're looking for (grouping type).
You should use a Dictionary.
public Enum EType
{
A,
B,
C
}
public class PatientData
{
public EType Type { get; set; }
public int Value {get; set; }
}
public class PatientManager
{
private readonly Dictionary<String, List<PatientData>> _patients = new Dictionary<String, List<PatientData>>();
public void AddPatientData(string name, EType type, int value)
{
var patientData = new PatientData
{
Type = type,
Value = value
};
List<PatientData> patientDatas;
if (!dictionary.TryGetValue(name, out patientDatas))
{
patientDatas = new List<PatientData>();
dictionary.Add(key, patientDatas);
}
_patientDatas.Add(patientData);
}
public void LoadData(string[] names, EType[] types, int[] values)
{
var iMax = Math.Min(names.Length, Math.Min(type.Length, values.Length));
for (var i = 0; i < iMax; i++)
{
AddPatientData(names[i], types[i], values[i]);
}
}
}

How to set objects name if I only have the number of enum

How to set objects name if I only have the number of enum!
See in code what I meanm Im bad to explain
//Working
//Not Working
Code
public enum CarColor
{
Red = 0,
Blue= 1,
}
public class CarColor
{
public virtual CarColor Id { get; set; }
}
public class Car
{
public virtual int Customnumber{ get; set; }
public virtual CarColor CarColorNumber{ get; set; }
}
Public SaveIt(Car car)
{
car.CarColorNumber= CarColor.Blue; //Working
car.CarColorNumber= 1; // not Workingm the color for blue
}
The supposedly problematic line already works:
// This compiles fine
car.CarColorNumber = 0;
It wouldn't compile for any integer value other than a constant of 0, however. There's an implicit conversion from a constant value of 0 to any enum type, but for anything else it's an explicit conversion. So for example:
int number = 0;
// number is a variable, not a constant expression, so you need to cast.
car.CarColorNumber = (CarColor) number;

Categories