How to create a Class List with different numbers of inputs in C# - c#

I'm working on my first real c# project and I have faced a problem with my way of creating List based on a Class, which I have no idea how to solve.
I’m trying to write some code, which takes an input file (txt/csv) of multiple constructions with multiple layers, put it into my program, and later write the constructions into a new txt/csv file.
When having the same numbers of layers, it works fine. But when the constructions have different numbers of layers it causes trouble and I get a “System.IndexOutOfRangeException”.
My question is: Can I make the Class which I’m basing my List on, dynamic (I don’t know if it is the technical term), so it work with different numbers of inputs? Both when Adding the construction to the program and when I write it to a new file?
My code is:
class Program
{
static void Main(string[] args)
{
// Filepath for the input and output file
string filePathIn_constructions = #"C:\Library\Constructions.txt";
string filePathOut = #"C:\Library\EPlus_Inputfile.txt";
// Creating a list of constructions based on the class. The list is made from the file "filePathIn_constructions"
List<Construction> allConstructions = new List<Construction>();
List<string> lines_constructions = File.ReadAllLines(filePathIn_constructions).ToList(); // add it to a list
// Adding all the data from the fil to the variable "allConstructions"
foreach (var line in lines_constructions)
{
string[] entries = line.Split(',');
Construction newConstruction = new Construction();
newConstruction.EIndex = entries[0];
newConstruction.Name = entries[1];
newConstruction.Layer1 = entries[2];
newConstruction.Layer2 = entries[3];
newConstruction.Layer3 = entries[4];
newConstruction.Layer4 = entries[5];
newConstruction.Layer5 = entries[6];
allConstructions.Add(newConstruction); // Add it to our list of constructions
}
List<string> output = new List<string>();
foreach (var x in allConstructions) // Printing the new
{
output.Add($"{x.EIndex}, {x.Name}, {x.Layer1}, {x.Layer2}, {x.Layer3}, {x.Layer4}, {x.Layer5}");
}
File.WriteAllLines(txtFilePathOut, output);
}
}
My Class for the Constructions is
public class Construction
{
public string EIndex { get; set; }
public string Name { get; set; }
public string Layer1 { get; set; }
public string Layer2 { get; set; }
public string Layer3 { get; set; }
public string Layer4 { get; set; }
public string Layer5 { get; set; }
}
An example of a input/output file could be
Construction,ConcreteWall,Concrete;
Construction,Brickwall1,Birck,Isulation,Brick;
Construction,Brickwall2,Birck,AirGap,Isulation,Brick;
Construction,Wood/Concrete Wall,Wood,Isulation,Concrete,Gypson;
Construction,Wood Wall,Wood,AirGap,Gypson,Isulaiton,Gypson;
I hope someone can help. Thanks.
Edit: I have to be able to excess the construction Name seperatly, because i'm using it to do some sorting of the.

public class Construction
{
public string EIndex { get; set; }
public string Name { get; set; }
public List<string> Layers { get; set; } = new List<string>();
}
foreach (var line in lines_constructions)
{
string[] entries = line.Split(',');
Construction newConstruction = new Construction();
newConstruction.EIndex = entries[0];
newConstruction.Name = entries[1];
for (int i=2; i < entries.Length; i++) {
newConstruction.Layers.Add(entries[i]);
}
allConstructions.Add(newConstruction);
}
foreach(var x in allConstuctions) {
File.AppendAllText(output, $"{x.EIndex}, {x.Name}, {string.Join(", ", x.Layers)}");
}

It is because you are trying to reach a cell of an array that doesn't exist (documentation)
In your input/output file you have lines that have between 3 and 7 values, and you are building an array entries out of those values. This means that you will have arrays with between 3 and 7 cells
The problem is that right after creating those arrays you try to access on every array the cells 0, 1, 2... up to the 7th, even for arrays that have only 3 cells!
What you could do to fix this in a simple way is to add columns to have the same number of separator on each lines (you defined the separator of your lines as column with line.Split(',')). This way, every arrays that you will create will always have 7 cells, even if the value inside is null

Related

C# + Copy JSON Data

I have the below JSON data stored in one of my fields.
I am want to copy this data in another new record however the guid's mentioned are not copied exactly as it is. I have a dictionary created in my code where these guid's are part of the key and value guid's against it must be updated in the new json.
I have written the code for it However just want to know if there is a better way of doing it.
{ "masterTable" :"tablename",
"selectedColumns":"f8a96c63-3d0d-ed11-82e5-002248189771,
dca1116d-410d-ed11-82e5- 002248189771"}
newtoOldGuids = {"4d6048ea-c40e-ed11-82e5-00224818919f|f8a96c63-3d0d-ed11-82e5-002248189771", "8a719554-9b0c-ed11-82e5-00224818919f"},
{"4d6048ea-c40e-ed11-82e5-00224818919f|dca1116d-410d-ed11-82e5- 002248189771","70e62e29-9b0c-ed11-82e5-00224818919f"}
So the new JSON should look like below -
{ "masterTable" :"tablename",
"selectedColumns":"8a719554-9b0c-ed11-82e5-00224818919f,
70e62e29-9b0c-ed11-82e5-00224818919f"}
Below is my C# code -
public class Filters
{
public string MasterTable { get; set; }
public string SelectedColumns { get; set; }
}
var filterJsonObj = JsonConvert.DeserializeObject<Filters>(filterJson);
List<string> colsList = filterJsonObj.SelectedColumns.Split(',').ToList();
List<string> newColsList = new List<string>();
foreach (var i in colsList)
{
var newguid = newtoOldGuids.Where(kvp => kvp.Key.Contains(i)).Select(kvp => kvp.Value).ToList();
newColsList.Add(newguid[0].ToString());
}
filterJsonObj.SelectedColumns = newColsList.Count > 0 ? string.Join(",", newColsList) : string.Empty;
return JsonConvert.SerializeObject(filterJsonObj);

Update column value of CSV in C#

In the coding, I want to replace the column value of CSV. However, it can`t replace the value in CSV.
CSV file:
"Name","Age"
"michael","16"
"miko","15"
"Tom","24"
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string text = File.ReadAllText(#"C:\test.csv");
TestDataModel users = new TestDataModel();
text = users.Name.Replace("m", "n");
File.WriteAllText(#"C:\test.csv", text);
}
public class TestDataModel
{
public string Name { get; set; }
public int Age { get; set; }
}
}
}
there is a lot of misconception in code you provided, and some of the solutions for your problem might not be begginer friendly.
Especially when they are not 'global' solutions. For your case I tried to explain parts of code in comments
using System.Text.RegularExpressions;
var csvFilePath = #"C:\test.csv";
// Split csv file into lines instead of raw text.
string[] csvText = File.ReadAllLines(csvFilePath);
var models = new List<TestDataModel>();
// Regex that matches your CSV file.
// Explained here: https://regex101.com/r/t589CW/1
var csvRegex = new Regex("\"(.*)\",\"(.*)\"");
for (int i = 0; i < csvText.Length; i++)
{
// Skip headers of file.
// That is: "Name","Age"
if (i == 0)
{
continue;
}
// Check for potential white spaces at the end of the file.
if (string.IsNullOrWhiteSpace(csvText[i]))
{
continue;
}
models.Add(new TestDataModel
{
// Getting a name from regex group match.
Name = csvRegex.Match(csvText[i]).Groups[1].Value,
// Getting an age from regex group and parse it into integer.
Age = int.Parse(csvRegex.Match(csvText[i]).Groups[2].Value),
});
}
// Creating headers for altered CSV.
string alteredCsv = "\"Name\",\"Age\"\n";
// Loop through your models to modify them as you wish and add csv text in correct format.
foreach (var testDataModel in models)
{
testDataModel.Name = testDataModel.Name.Replace('m', 'n');
alteredCsv += $"\"{testDataModel.Name}\",\"{testDataModel.Age}\"\n";
}
var outputFilePath = #"C:\test2.csv";
File.WriteAllText(outputFilePath, alteredCsv);
public class TestDataModel
{
public string Name { get; set; }
public int Age { get; set; }
}
However this answer contains many topics that you might want to get familiar with such as:
Regex/Regex in C#
Data Serialization/Deserialization
Working with Linq
String templates
I/O Operations
Try this
public static void Replace()
{
string text = File.ReadAllText(#"C:\test.csv");
string _text = text.Replace("m", "n");
File.WriteAllText(#"C:\New_test.csv", _text);
}

Reading multiple records kept in a text file

Basically i have the user open a text document that is formatted like this currently.
Burger.jpg,Double Down KFC,Food,30/06/95,This is a burger
it then splits the info into an array then into variables and then into text boxes.
obviously if i wanted multiple records i may have to format it differently, (thats what i need help with)
But if i had it like this what would be the most efficient way of taking these records from the text file and storing them separately so i can flick through them. For example with a combo box on my form. When the record is selected the form populates with that records data.
multiple records:
Burger.jpg,Double Down KFC,Food,30/06/95,This is a burger
Person.jpg,Smile,People,23/06/95,This is a Person
Here is my code currently for this part.
private void LoadFile()
{
StreamReader reader = new StreamReader(fileName);
content = reader.ReadLine();
doc = content.Split(',');
filename = Convert.ToString(doc[0]);
fileNameTextBox.Text = doc[0];
description = doc[1];
descriptionTextBox.Text = doc[1];
category = doc[2];
categoryComboBox.Text = doc[2];
//dateTaken = Convert.ToDouble(doc[3]);
dateTakenTextBox.Text = doc[3];
comments = doc[4];
commentsTextBox.Text = doc[4];
}
This code currently works but only for the first record as it is using one array, and i obviously will need multiple ways of storing the other lines.
I Think the best option if i was going to give it a guess would be to use a List of some sort with a Class that generates Records, but that is where i am stuck and need help.
(usually my questions on here get downvoted as i am not concise enough if that is the case comment and i will try to alter my question.
Thanks everyone.
I would create a class that holds the information of a record
public class ImageInfo
{
public string FileName { get; set; }
public string Description { get; set; }
public string Category { get; set; }
public DateTime Date { get; set; }
public string Comments { get; set; }
public override string ToString()
{
return FileName;
}
}
Now you can write a method that returns the image infos
public List<ImageInfo> ReadImageInfos(string fileName)
{
string[] records = File.ReadAllLines(fileName);
var images = new List<ImageInfo>(records.Length);
foreach (string record in records) {
string[] columns = record.Split(',');
if (columns.Length >= 5) {
var imageInfo = new ImageInfo();
imageInfo.FileName = columns[0];
imageInfo.Description = columns[1];
imageInfo.Category = columns[2];
DateTime d;
if (DateTime.TryParseExact(columns[3], "dd/MM/yy",
CultureInfo.InvariantCulture, DateTimeStyles.None, out d))
{
imageInfo.Date = d;
}
imageInfo.Comments = columns[4];
images.Add(imageInfo);
}
}
return images;
}
Now you can fill the textboxes with one of these records like this
List<ImageInfo> images = ReadImageInfos(fileName);
if (images.Count > 0) {
ImageInfo image = images[0];
fileNameTextBox.Text = image.FileName;
descriptionTextBox.Text = image.Description;
categoryComboBox.Text = image.Category;
dateTakenTextBox.Text = image.Date.ToShortDateString();
commentsTextBox.Text = image.Comments;
}
The advantage of this approach is that the two operations of reading and displaying the records are separate. This makes it easier to understand and modify the code.
You can add ImageInfo objects to a ComboBox or ListBox directly instead of adding file names if you override the ToString method in the ImageInfo class.
public override string ToString()
{
return FileName;
}
Add the items to a combo box like this:
myComboBox.Items.Add(image); // Where image is of type ImageInfo.
You can retrieve the currently selected item with:
ImageInfo image = (ImageInfo)myComboBox.SelectedItem;
Most likely you will be doing this in the SelectedIndexChanged event handler.
void myComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
ImageInfo image = (ImageInfo)myComboBox.SelectedItem;
myTextBox.Text = image.FileName;
}
Create a class that resembles a row of your data, then iterate over the file, making your split and constructing a new class instance with your split data. Store this in a List<> (or some other appropriate structure) ensure you store it such that it can be referenced later. Don't change your UI as you are loading and parsing the file (as Mike has suggested), also as mike suggests you need to read until the EOF is reached (plenty of examples of this on the web) MSDN example.
Also, streamreader implements IDisposable, so you need to dispose of it, or wrap it in a using statement to clean up.
Example class, you could even pass the row in as a constructor argument:
public class LineItem
{
public string FileName { get; set; }
public string Description { get; set; }
public string Category { get; set; }
public DateTime DateTaken { get; set; }
public string Comments { get; set; }
public LineItem(string textRow)
{
if (!string.IsNullOrEmpty(textRow) && textRow.Contains(','))
{
string[] parts = textRow.Split(',');
if (parts.Length == 5)
{
// correct length
FileName = parts[0];
Description = parts[1];
Category = parts[2];
Comments = parts[4];
// this needs some work
DateTime dateTaken = new DateTime();
if (DateTime.TryParse(parts[3], out dateTaken))
{
DateTaken = dateTaken;
}
}
}
}
}
Your code is not iterating through the records within the file.
You want to continue reading until the end of the file.
while (content != eof)
{
// split content
// populate text boxes
}
But this will overwrite your text boxes with each pass of the loop.
Also, you want to separate your code - do not mix I/O process with code that updates the UI.
The name of the method implies you are loading a file, but the method is doing far more than that. I would suggest changing the method to read the file, split each record into a class object which then gets stored into an array - and return that array.
A separate method will take that array and populate your table or grid or whatever is in the UI. Ideally, you have the gridview bind to the array.
If you keep all your entries the same:
name,food,type,blah blah
name,food,type,blah blah
you can add another split into your code:
line = content.Split('\n');
foreach (line in filename)
{
doc = line.Split(',');
//do stuff...
As for the option for string multiple entries, a method I have used is implementing a list of Models:
class ModelName
{
string Name { get; set; }
string foodType { get; set; }
//etc...
public void ModelName()
{
Name = null;
foodType = null;
//etc...
}
}
List<Model> ModelList;
foreach (line in filename)
{
doc = line.Split(',');
Model.Name = doc[1];
//etc...
And have a different list, and a different Model for each type of entry (person or food)

Storing DataGrid in List

With my program I'm trying to automatize another program of which there can be multiple instances. I've already written functionality that will watch the processlist and detect all processes of the program that I want to automatize.
It will store some basic informations about found instances into this ConcurrentDictionary which has its ProcessId as key and the class ProgramToWatch as value:
public static ConcurrentDictionary<int, ProgramToWatch> ProgramToWatchDictionary = new ConcurrentDictionary<int, ProgramToWatch>();
public class ProgramToWatch
{
public string ListItemName { get; set; }
public Process BEProcess { get; set; }
public string BEMainWindowTitle { get; set; }
public Application BEApplication { get; set; }
public Window BEWindow { get; set; }
public bool isLoggedIn { get; set; }
public List<ProgramToWatchDataGrid> BEDataGrid = new List<ProgramToWatchDataGrid>();
}
Now the part I am having problems with. The program I want to watch has a DataGridView which I want to copy into my dictionary. For this I have the BEDataGrid List. The list is using this class as its type:
public class ProgramToWatchDataGrid
{
public int ListID { get; set; }
public string Name { get; set; }
public string Mail { get; set; }
}
Now to store it, I create another instance of the ProgramToWatchDataGrid (called updateGrid), write all the data I read into it, and place this into my Dictionary (I simplified). To do this, I iterate through the DataGrid (first while loop), row for row and copy the updateGrid to my Dictionary - in the second while loop I display the values to verify:
public void ReadDataGridView(int ProcessId)
{
ProgramToWatchDataGrid updateGrid = new ProgramToWatchDataGrid();
//read and store every row
int i=0;
while(i<=totalRowsInGrid)
{
updateGrid.ListId = DataGrid.Rows[i].Cells[0].Value;
updateGrid.Name = DataGrid.Rows[i].Cells[1].Value;
updateGrid.Mail = DataGrid.Rows[i].Cells[2].Value;
ProgramToWatchDictionary[ProcessID].BEDataGrid.Insert(i, updateGrid);
Display(ProgramToWatchDictionary[ProcessID].BEDataGrid[i].Mail);
}
Display("Elements: " + ProgramToWatchDictionary[ProcessID].BeDataGrid.Count);
//display every rows mail
i=0;
while(i<=totalRowsInGrid)
{
Display("HI: " + ProgramToWatchDictionary[ProcessID].BEDataGrid[i].Mail);
i++;
}
}
The way I understand it, the Information rows I read should now be located in ProgramToWatchDictionary[ProcessID].BEDataGrid[accordingRow] because I inserted the Information at that place.
The strange thing is, that this output will be produced:
[01:19] christoferlindstrm#yahoo.com
[01:19] eliseisaksson#yahoo.com
[01:19] peter#pan.com
[01:19] Elements: 3
[01:19] HI: peter#pan.com
[01:19] HI: peter#pan.com
[01:19] HI: peter#pan.com
So right after I've inserted it, the List contains the right value. But after it will always be the last value that was read? Why does this happen and how can I fix this?
Some help would be greatly appreciated!
Got it.
You should create the instance of the object to be added in the while, otherwise you are using only one instance which happens to get different values in your cycle. And of course it will end up with the last value you have inserted.
public void ReadDataGridView(int ProcessId)
{
ProgramToWatchDataGrid updateGrid = null;
//read and store every row
int i=0;
while(i<=totalRowsInGrid)
{
//create a new instance
updateGrid = new ProgramToWatchDataGrid();
updateGrid.ListId = DataGrid.Rows[i].Cells[0].Value;
updateGrid.Name = DataGrid.Rows[i].Cells[1].Value;
updateGrid.Mail = DataGrid.Rows[i].Cells[2].Value;
ProgramToWatchDictionary[ProcessID].BEDataGrid.Insert(i, updateGrid);
Display(ProgramToWatchDictionary[ProcessID].BEDataGrid[i].Mail);
}
Display("Elements: " + ProgramToWatchDictionary[ProcessID].BeDataGrid.Count);
//display every rows mail
i=0;
while(i<=totalRowsInGrid)
{
Display("HI: " + ProgramToWatchDictionary[ProcessID].BEDataGrid[i].Mail);
i++;
}
}

How to shuffle multiple related arrays?

I have some unusual I need to do. I am wondering if anyone can think of an easy
way to make the change that I need. What I have is a
public class Report
{
public string[] Text { get; set; }
public string[] Image { get; set; }
public string[] Explanation { get; set; }
}
The report class can have any number of Texts, Images and Explanations and the size of each array is always the consistent but maybe be different for each report instance.
What I need to do is to be able to sort the array elements in a random order. So for example I might have
Report.Text[0] = "text0";
Report.Text[1] = "text1";
Report.Text[2] = "text2";
Report.Image[0] = "img0";
Report.Image[1] = "img1";
Report.Image[2] = "img2";
Report.Explanation[0] = "exp0";
Report.Explanation[1] = "exp1";
Report.Explanation[2] = "exp2";
then after sorting
Report.Text[0] = "text2";
Report.Text[1] = "text0";
Report.Text[2] = "text1";
Report.Image[0] = "img2";
Report.Image[1] = "img0";
Report.Image[2] = "img1";
Report.Explanation[0] = "exp2";
Report.Explanation[1] = "exp0";
Report.Explanation[2] = "exp1";
Can anyone think of a simple way to do this? All I can think of is that I need to create a
new temporary object of the same size and do some kind of swapping. But I am not sure how
to randomize. The reason I am asking is just in case someone has had this need in the past.
I would strongly recommend that you refactor this to create a single class to encapsulate the { Text, Image, Explanation } tuple. At that point, the code will be cleaner and it'll be trivial to reorder the values. Heck, you may not even need a Report type at that point... you may just be able to have a List<ReportItem> or whatever. You'd only need a separate Report type if you wanted to add extra behaviour or data to tie things together.
(As an aside, I hope you don't really have public fields for these to start with...)
If you then have a question around shuffling a single collection, a modified Fisher-Yates shuffle is probably the easiest approach. You could do this with the multiple arrays as well, but it wouldn't be nice - and would have to be specific to Report... whereas you could easily write a generic Fisher-Yates implementation based on IList<T>. If you search on Stack Overflow, you should easily be able to find a few existing implementations :)
If you choose to change your class to the following:
public class Report
{
public string Text { get; set; }
public string Image { get; set; }
public string Explanation { get; set; }
}
You could then do this using an extension method:
(See answer on this SO question)
Then call it this way:
List<Report> reports = new List<Report> { /* create list of reports */ }
Random rnd = new Random();
foreach (Report r in reports.Shuffle(rnd)) {
/* do something with each report */
}
Why don't you create a class
public class Report
{
public string Text { get; set; }
public string Image { get; set; }
public string Explanation { get; set; }
}
and then create a List of those objects and manage it through the list properties:
IList<Report> yourList = new List<Report>()
Here is my solution
class StringWrapper
{
public int Index;
public string Str;
}
public string[] MixArray(string[] array)
{
Random random = new Random();
StringWrapper[] wrappedArray = WrapArray(array);
for (int i = 0; i < wrappedArray.Length; i++)
{
int randomIndex = random.Next(0, wrappedArray.Length - 1);
wrappedArray[i].Index = randomIndex;
}
Array.Sort(wrappedArray, (str1, str2) => str1.Index.CompareTo(str2.Index));
return wrappedArray.Select(wrappedStr => wrappedStr.Str).ToArray();
}
private StringWrapper[] WrapArray(string[] array)
{
int i = 0;
return array.Select(str => new StringWrapper {Index = ++i, Str = str}).ToArray();
}
Then you can call MixArray for each Report object for each property you wand to randomize.
I am not sure I am fond of this direction, but ...
To do exactly what you ask (the law, not the spirit of the law), you will have to add additional arrays and pull items over. In addition, for each array, you will need a List or similar to store the items you have already randomly pulled over. After that, things are simple. Use the Random class to create random numbers, check if the item has already been moved (using the List), if not store the result in the new array/list, add the value to your List to make sure you do not move the same item twice. Once everything is moved, set this new array to the old array.
Now, what is the business reason for randomizing? That might affect whether or not this is a good idea.
ADDED:
After examination of skeet's response, here is a way to solve this if you can use the following type of class:
public class Report {
public string Text { get; set; }
public string Image { get; set; }
public string Explanation { get; set; }
}
Here is one "down and dirty" type of sort:
private static SortedList<int, Report> SortRandomly(List<Report> reports)
{
Random rnd = new Random((int)DateTime.Now.Ticks);
List<int> usedNumbers = new List<int>();
SortedList<int, Report> sortedReports = new SortedList<int, Report>();
int maxValue = reports.Count;
foreach(Report report in reports)
{
bool finished = false;
int randomNumber = 0;
//Get unique random (refactor out?)
while(!finished)
{
randomNumber = rnd.Next(0, maxValue);
if(!usedNumbers.Contains(randomNumber))
{
finished = true;
usedNumbers.Add(randomNumber);
}
}
sortedReports.Add(randomNumber, report);
}
return sortedReports;
}
Note, you can also work to keep the sort in order and randomly picking from the original list, which means you can, in theory, keep it as a list.
private static List<Report> SortRandomly(List<Report> reports)
{
Random rnd = new Random((int)DateTime.Now.Ticks);
List<Report> outputList = new List<Report>();
List<int> usedNumbers = new List<int>();
int maxValue = reports.Count-1;
while(outputList.Count < reports.Count)
{
int randomNumber = rnd.Next(0, maxValue);
if(!usedNumbers.Contains(randomNumber))
{
outputList.Add(reports[randomNumber]);
}
}
return outputList;
}
Even better, consider sorting the list of numbers first and then grabbing the reports, in an order manner. Once again, the above are down and dirty implementations and using the specific requirements will certainly refine the algorithms.

Categories