How to place values from struct to an array? - c#

I'm trying to do it like bellow, but for next operations i would like to output an array that consist of 3-5 structs.
I would like to do it like : string[] my_array = {struct1,struct2,struct3}; but don't know how to do it correct.
public struct student
{
public string Name { get; set; }
public string Last_Name { get; set; }
public DateTime Birthday { get; set; }
public string Address { get; set; }
public string City { get; set; }
public int Zip { get; set; }
public string Country { get; set; }
}
class H
{
static void Main(string[] args)
{
student student_info = new student();
student_info.Name = "Mike";
student_info.Last_Name = "Johnson";
student_info.Birthday = new DateTime(1983, 12, 03);
student_info.Address = "Baker str. 84/4a";
student_info.City = "New LM";
student_info.Zip = 90541;
student_info.Country = "Paris";
string[] my_array = { student_info.Name, student_info.Last_Name, student_info.Birthday.ToString(), student_info.Address, student_info.City, student_info.Zip.ToString(), student_info.Country };
for (int counter = 0; counter < my_array.Length; counter++)
{
Console.WriteLine(my_array[counter]);
}
}
}

I'm not completely sure I understand what you're doing. But here's my best guess.
If the objects will all be of the same struct, you can just use that.
student[] args = new [] { struct1, struct2, struct3 };
If they aren't the same type, the greatest common denominator between three structs like this will be object. So,
object[] args = new object[] { struct1, struct2, struct3 };
If you'd like, on the other hand, to combine the three structs into a single string array as you've shown us, that's a little different, and I can show you if you confirm that that is actually what you were looking for.

You can create an array of the struct.
student[] my_array = new student[] {struct1,struct2,struct3};

Related

How to convert json file to List<MyClass>

I am trying to create a log file in json format from a List.
my class for list is
public class ChunkItem
{
public int start { get; set; }
public int end { get; set; }
}
public class DownloadItem
{
public int id { get; set; }
public string fname { get; set; }
public string downloadPath { get; set; }
public int chunkCount { get; set; }
public ChunkItem[] chunks { get; set; }
public DownloadItem(int _id, string _fname, string _downloadPath, int _chunkCount, ChunkItem[] _chunks)
{
id = _id;
fname = _fname;
downloadPath = _downloadPath;
chunkCount = _chunkCount;
chunks = _chunks;
}
}
creating a json file from this class works fine
ChunkItem[] chunks = new ChunkItem[2];
chunks[0] = new ChunkItem();
chunks[0].start = 0;
chunks[0].end = 0;
chunks[1] = new ChunkItem();
chunks[1].start = 0;
chunks[1].end = 0;
List<DownloadItem> lst = new List<DownloadItem>();
lst.Add(new DownloadItem(0, "", "", 2, chunks));
lst.Add(new DownloadItem(1, "aaa", "sss", 2, chunks));
lst.Add(new DownloadItem(2, "bbb", "ddd", 2, chunks));
string json = JsonConvert.SerializeObject(lst);
System.IO.File.WriteAllText(logPath, json);
I want to read the file to same class list and do some updates or add new lines
I can read the file to a string but cannot create a new list
how can I convert string (read json file) to List<DownloadItem> new list
You need to read all the contends from the file and deserialize the json string to List<DownloadItem>
var jsonData = File.ReadAllText(filePath)
var list = JsonConvert.DeserializeObject<List<DownloadItem>>(jsonData);
Clas DownloadItem is missing a default parameterless constructor.
I use Newtonsoft, where creating the instances and filling them is simple
var result = Newtonsoft.Json.JsonConvert.DeserializeObject<MyClass>(jsonString);

List overwriting previous added Objects when a new Object is added

I'm looping through some logic for a program I'm making that reads text through a .txt file and every time I get to the place where the algorithm adds a Class Object I created it works but then the next time it hits it the previous object gets its data changed to the object currently being added and so on.
Here is a Snippet of code for preface this is inside While loop and nested in 3 if statements.
Question: Why is it overwriting all the other entries?
My logic is 100% working I ran tests on it for over 10 hours with many breakpoints also please go easy on me I'm semi proficient at C#
if (Att == a1)
{
Student s1 = new Student();
s1.Eid = Eid;
s1.Name = Name;
s1.Attempt1 = att1;
AllStudents.Add(s1);
//AllStudents.Add(new Student(Eid,Name, att1));
Eid = line;
Att = "";
qnum = 1;
counter = 1;
}
Here is my Student class
public class Student
{
public string Eid { get; set; }
public string Name { get; set; }
public string[] Attempt1 { get; set; }
public string[] Attempt2 { get; set; }
public string[] Attempt3 { get; set; }
public string[] Att1filler = { "n/a", "n/a", "n/a", "n/a", "n/a", "n/a" };
public string[] Att2filler = {"n/a","n/a","n/a","n/a","n/a","n/a"};
public string[] Att3filler = {"n/a","n/a","n/a","n/a","n/a","n/a"};
public int FinalGrade { get; set; }
public int Grade1 { get; set; }
public int Grade2 { get; set; }
public int Grade3 { get; set; }
public int Grade4 { get; set; }
public Student()
{
FinalGrade = 0;
Attempt1 = Att1filler;
Attempt2 = Att2filler;
Attempt3 = Att3filler;
}
public Student(string Eagid, string name, string[] Att1)
{
Eid = Eagid;
Name = name;
Attempt1 = Att1;
Attempt2 = Att2filler;
Attempt3 = Att3filler;
FinalGrade = 0;
}
public Student(string Eagid, string name, string[] Att1, string[] Att2)
{
Eid = Eagid;
Name = name;
Attempt1 = Att1;
Attempt2 = Att2;
Attempt3 = Att3filler;
FinalGrade = 0;
}
public Student(string Eagid, string name, string[] Att1, string[] Att2, string[] Att3)
{
Eid = Eagid;
Name = name;
Attempt1 = Att1;
Attempt2 = Att2;
Attempt3 = Att3;
FinalGrade = 0;
}
}
And finally this is how I declared my List
public List<Student> AllStudents = new List<Student>();
also the AllStudents.add(new Student(Eid,Name, att1)); is from another solution i found that still did not work for me.
I figured it out. Learned my lesson of passing by references vs passing by value. make sure if your algorithm is looping that anything that is initialized by new and is used inside the loop is re-initialized inside the loop so you don't just pass the same reference for each object.(sorry if this answer isn't 100% I'm running on 2 hours of sleep trying to get this project done!)

{get;set;} for arrayList in c# WindowsForms

Is there any solution to use set and get for arraylist ?
I want to put all of my arraylists in one class but then i need them to fill a bidimensional array to use them. (1 list=1 column)
I want to put this
ArrayList listanume = new ArrayList();
In this :
class Beneficiar
{}
And use it to fill an bidimensional array like
listanume -> a[i,0]
I really don't know how to say it right, but this is the idea...
You should do something like that
class Program
{
public static void Main(string[] args)
{
List<Account> accounts = new List<Account>();
Account a1 = new Account { Name = "Peter", Password = "lalala", Mail = "mail#yahoo.com", TotalSold = 100M };
accounts.Add(a1);
}
}
public class Account
{
public string Name { get; set; }
public string Password { get; set; }
public string Mail { get; set; }
public decimal TotalSold { get; set; }
}
To access any account by some field you can do this
string searchNameString = "Peter";
var foundAccount = accounts.FirstOrDefault(x => x.Name == searchNameString);
if (foundAccount != null)
{
//Code which uses found account
}
//Here you will get all accounts with total sold > 1000. You can then iterate over them with for or foreach
var foundAccountsByTotalSold = accounts.Where(x => x.TotalSold > 1000);

Casting List Type at Runtime C# Reflection

I've been working on using reflection but its very new to me still. So the line below works. It returns a list of DataBlockOne
var endResult =(List<DataBlockOne>)allData.GetType()
.GetProperty("One")
.GetValue(allData);
But I don't know myType until run time. So my thoughts were the below code to get the type from the object returned and cast that type as a list of DataBlockOne.
List<DataBlockOne> one = new List<DataBlockOne>();
one.Add(new DataBlockOne { id = 1 });
List<DataBlockTwo> two = new List<DataBlockTwo>();
two.Add(new DataBlockTwo { id = 2 });
AllData allData = new AllData
{
One = one,
Two = two
};
var result = allData.GetType().GetProperty("One").GetValue(allData);
Type thisType = result.GetType().GetGenericArguments().Single();
Note I don't know the list type below. I just used DataBlockOne as an example
var endResult =(List<DataBlockOne>)allData.GetType() // this could be List<DataBlockTwo> as well as List<DataBlockOne>
.GetProperty("One")
.GetValue(allData);
I need to cast so I can search the list later (this will error if you don't cast the returned object)
if (endResult.Count > 0)
{
var search = endResult.Where(whereExpression);
}
I'm confusing the class Type and the type used in list. Can someone point me in the right direction to get a type at run time and set that as my type for a list?
Class definition:
public class AllData
{
public List<DataBlockOne> One { get; set; }
public List<DataBlockTwo> Two { get; set; }
}
public class DataBlockOne
{
public int id { get; set; }
}
public class DataBlockTwo
{
public int id { get; set; }
}
You might need something like this:
var endResult = Convert.ChangeType(allData.GetType().GetProperty("One").GetValue(allData), allData.GetType());
Just guessing, didn't work in C# since 2013, please don't shoot :)
You probably want something like this:
static void Main(string[] args)
{
var one = new List<DataBlockBase>();
one.Add(new DataBlockOne { Id = 1, CustomPropertyDataBlockOne = 314 });
var two = new List<DataBlockBase>();
two.Add(new DataBlockTwo { Id = 2, CustomPropertyDatablockTwo = long.MaxValue });
AllData allData = new AllData
{
One = one,
Two = two
};
#region Access Base Class Properties
var result = (DataBlockBase)allData.GetType().GetProperty("One").GetValue(allData);
var oneId = result.Id;
#endregion
#region Switch Into Custom Class Properties
if (result is DataBlockTwo)
{
var thisId = result.Id;
var thisCustomPropertyTwo = ((DataBlockTwo)result).CustomPropertyDatablockTwo;
}
if (result is DataBlockOne)
{
var thisId = result.Id;
var thisCustomPropertyOne = ((DataBlockOne)result).CustomPropertyDataBlockOne;
}
#endregion
Console.Read();
}
public class AllData
{
public List<DataBlockBase> One { get; set; }
public List<DataBlockBase> Two { get; set; }
}
public class DataBlockOne : DataBlockBase
{
public int CustomPropertyDataBlockOne { get; set; }
}
public class DataBlockTwo : DataBlockBase
{
public long CustomPropertyDatablockTwo { get; set; }
}
public abstract class DataBlockBase
{
public int Id { get; set; }
}

Convert arraylist to a list of dictionaries?

Does somebody know how to convert an arraylist to a list of dictionaries?
What do I have? I have an ArrayList (list) with a lot of strings:
foreach (string s in list)
{
Console.WriteLine(s);
}
output:
klaus
male
spain
lissy
female
england
peter
male
usa
...
As we see there is an order. The first entry is a NAME, second GENDER, third COUNTRY and then again NAME, GENDER... and so on.
Now for clarity I would like to store these attributes in a List of Dictionaries. Every List entry should be 1 Dictionary with these 3 Attributes. Is this a good idea? Whats the easiest way? I just search something to store this list in a better looking collection that is later easiert to handle. I have this:
List<Dictionary<string, string>> dlist = new List<Dictionary<string, string>>();
const int separate = 3;
foreach (string s in list)
{
//add list entries to dlist?
}
No it's not a good idea. Define a class.
At least something like this:
class Person
{
public string Name { get; set; }
public string Gender { get; set; }
public string Country { get; set; }
}
Even better would be to use an enum for Gender, and possibly a class (built-in or custom) for the country.
Anyway, to populate a collection with the above class, you'd use something like:
List<Person> result = new List<Person>();
for (int i = 0; i < list.Count; i += 3) {
result.Add(
new Person { Name = list[i], Gender = list[i+1], Country = list[i+2] });
}
Note that this loop lacks error checking on the count of items in the list, which should be a multiple of three.
enum Gender
{
Male = 0,
Female = 1
}
class Person
{
public string Name { get; set; }
public Gender Gender { get; set; }
public string Country { get; set; }
public Person(string name, Gender gender, string country)
{
this.Name = name;
this.Gender = gender;
this.Country = country;
}
}
Usage:
List<Person> persons = new List<Person>();
Person person;
for (int i = 0; i < list.Count; i += 3) {
{
person = new Person(list[i], (Gender)Enum.Parse(typeof(Gender), list[i+1], true), list[i+2]);
persons.add(person);
}
I would recommend using a class to encapsulate your entry:
class Entry
{
public String Name { get; set; }
public String Gender { get; set; }
public String Country { get; set; }
}
Then add to a list of Entrys
List<Entry> elist = new List<Entry>();
for (int i = 0; i < list.Count; i += 3)
{
var ent = new Entry() { Name = list[i],
Gender = list[i+1],
Country = list[i+2]};
elist.Add(ent);
}
Or you could use Tuples:
List<Tuple<string, string, string>> tlist =
new List<Tuple<string, string, string>>();
for (int i = 0; i < list.Count; i += 3)
{
Tuple<string,string, string> ent
= new Tuple<string,string,string>(list[i], list[i+1], list[i+2]);
tlist.Add(ent);
}
the simplest way to implement that - it's create a new class for representing someone in you list with 3 props:
public class Someone {
public string Name { get; set; }
public string Gender { get; set; }
public string Country { get; set; }
}
And than you can fill your destination list with Someone entries:
List<Someone> dList = new List<Someone>();
for(int i = 0; i < list.Count; i += 3)
dList.Add(new Someone() { Name = list[i], Gender = list[i+1], Country = list[i+2] });
p.s. this code may contain errors because I don't have access to computer with VS installed.
You may have a class to hold the data like:
public class Info
{
public string Name { get; set; }
public string Gender { get; set; }
public string Country { get; set; }
}
then you can have a dictionary like this
Dictionary<int, Info> infoDict = new Dictionary<int, Info>();
then you can start reading and prepare the dictionary.
var listSrc = new List<string>
{
"klaus",
"male",
"spain",
"lissy",
"england",
"female",
"peter",
"usa",
"male",
};
var dlist = new List<Dictionary<string, string>>();
for (var i = 0; i < listSrc.Count; i++)
{
var captions = new List<string>
{
"Name",
"Gender",
"Country"
};
var list = listSrc.Take(3).ToList();
listSrc.RemoveRange(0, 3);
dlist.Add(list.ToDictionary(x => captions[list.IndexOf(x)], x => x));
}
Its simple. You are working for a class that contains three data variables named :
String name;
String gender;
String country;
So make a class that contains all three of these variables. As for eg:
class Dictnary
{
public Dictnary(String nameFromCall, String genderFromCall, String countryFromCall)
{
this.name = nameFromCall;
this.gender = genderFromCall;
this.country = countryFromCall;
}
}
To answer the question in the title, this is probably the most succinct way to do the conversion:
for (int i = 0; i < list.Count; i += 3) {
dlist.Add(new Dictionary<string, string>() {
{ "name", (string)list[i] },
{ "gender", (string)list[i+1] },
{ "country", (string)list[i+2] }
});
}
(If you switch from an ArrayList to a List<string>, you can drop the (string) cast.)
That said, unless you really need a dictionary for some technical reason, your problem is better solved using one of the class-based approaches suggested in the other answers.

Categories