finding max value in a c# array - c#

I am making a program in c# that will take in a list of names and scores from a text document, get the score on its own and then find the highest of the scores. I can separate the name from the score when it is just one but as soon as I try make it an array I do not have any idea what I am doing.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
System.IO.File.Exists(#"U:\StudentExamMarks.txt");
string[] text = System.IO.File.ReadAllLines(#"U:\StudentExamMarks.txt");
int a = 0;
string[] results = new string[a];
for(int i=0;i<text.Length ; i++ )
{
int x = text[i].LastIndexOf("\t");
int y = text[i].Length;
int z = (y - (x + 1));
results[a] = text[i].Substring((x+1), (z));
a++;
Console.WriteLine("{0}", results);
}
}
}
This is what I have so far
the list is as follows
John Cross 100
Christina Chandler 105
Greg Hamilton 107
Pearl Becker 111
Angel Ford 115
Wendell Sparks 118
like I said when I attempted it without an array I can get it to display the 100 from the first result. I also do not know how when I find the largest result how to link it back to the students name.

I suggest to use a class to hold all properties, that improves readability a lot:
public class StudentExam
{
public string StudentName { get; set; }
public int Mark { get; set; }
}
and following to read all lines and to fill a List<StudentExam>:
var lines = File.ReadLines(#"U:\StudentExamMarks.txt")
.Where(l => !String.IsNullOrWhiteSpace(l));
List<StudentExam> studentsMarks = new List<StudentExam>();
foreach (string line in lines)
{
string[] tokens = line.Split('\t');
string markToken = tokens.Last().Trim();
int mark;
if (tokens.Length > 1 && int.TryParse(markToken, out mark))
{
StudentExam exam = new StudentExam{
Mark = mark,
StudentName = String.Join(" ", tokens.Take(tokens.Length - 1)).Trim()
};
studentsMarks.Add(exam);
}
}
Now it's easy to get the max-mark:
int maxMark = studentsMarks.Max(sm => sm.Mark); // 118

To find the highest score, you can use Linq with Regex like this
var lines = new[] {
"John Cross 100",
"Christina Chandler 105",
"Greg Hamilton 107",
"Pearl Becker 111"
};
var maxScore = lines.Max(l => int.Parse(Regex.Match(l, #"\b\d+\b").Value));
Here, I'm assuming you have read the file correctly into lines and all of them has a valid int value of the score.

If the end of each entry is always a space followed by the student's score, you can use a simple substring:
int max = text.Max(x => Convert.ToInt32(x.Substring(x.LastIndexOf(' '))));
For each entry, create a substring that starts at the last index of ' ' and then convert that to an integer. Then return the max of those values.

Related

C# append text to a certain line

I try to build some table inside a text file which
look like this:
Name Grade
--------------------
John 100
Mike 94
...
...
I have this bunch of code:
List<string> NamesList = new List<string>();
List<int> Grades = new List<int>();
Grades.Add(98);
Grades.Add(100);
NamesList.Add("John");
NamesList.Add("Alon");
if (NamesList.Count() == Grades.Count())
{
var length = NamesList.Count();
var min = Grades.Min();
var max = Grades.Max();
using (System.IO.StreamWriter myF =
new System.IO.StreamWriter(#"C:\Users\axcel\textfolder\myFile.txt", true))
{
for (int i = 0; i < length; i++)
{
if (i == 0)
{
myF.WriteLine("Name Age Grade");
myF.WriteLine("==================================");
}
myF.WriteLine(NamesList.ElementAt(i));
myF.WriteLine(" ");
myF.WriteLine(Grades.ElementAt(i));
}
}
}
but my problem is that writing the grades after the names it is writing in a new line. I thought of writing it together to a string and to streaming it but I want to avoid an extra computing...
How can I solve it?
WriteLine() always add a new line after your text. So in your case it should be
myF.Write(NamesList.ElementAt(i));
myF.Write(" ");
myF.WriteLine(Grades.ElementAt(i));
var students = new List<(string name, int age, int grade)>()
{
("John", 21, 98),
("Alon", 45, 100)
};
students.Add(("Alice", 35, 99));
using (var writer = new StreamWriter("myFile.txt"))
{
writer.WriteLine(string.Join("\t", "Name", "Age", "Grade"));
foreach(var student in students)
{
writer.WriteLine(string.Join("\t", student.name, student.age, student.grade));
}
}
As some comments have suggested you could use a Student class to group name, age and grade. In this example I've used a Value Tuple instead.
You can see how it improves the readability of the code and you can focus on the problem you are actually trying to solve. You can reduce your write operation to a simple, readable expression - meaning you are less likely to make mistakes like mixing up Write and WriteLine.
You can always align the text by using string interpolation alignment.
To follow some of the comments, I also urge you to build a class holding the values.
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
public int Grade { get; set; }
}
And here is the code using string interpolation alignment
var students = new List<Student>
{
new Student {Name = "John", Age = 10, Grade = 98},
new Student {Name = "Alon", Age = 10, Grade = 100}
};
var minGrade = students.Min(s => s.Grade);
var maxGrade = students.Max(s => s.Grade);
using (var myF = new System.IO.StreamWriter(#"C:\Users\axcel\textfolder\myFile.txt", true))
{
myF.WriteLine($"{"Name",-15}{"Age",-10}{"Grade",5}");
myF.WriteLine("==============================");
foreach (var student in students)
{
myF.WriteLine($"{student.Name,-15}{student.Age,-10}{student.Grade,5}");
}
}
This will produce the following result:
Name Age Grade
==============================
John 10 98
Alon 10 100
Positive numbers are right-aligned and negative numbers are left-aligned
You can read more about it on the string interpolation page at Microsoft Docs
To solve the issue you are having, you could just use:
myF.WriteLine(NamesList.ElementAt(i) + " " + Grades.ElementAt(i));
However the code you provided would benefit from being modified as described in the comments (create a class, use FileHelpers, etc.)
Solution 1:
Why you are not trying the concatenating the two string like:
string line = NamesList.ElementAt(i) + " " + Grades.ElementAt(i);
myF.WriteLine(line);
OR
Solution 2:
What you are using is WriteLine("Text") function which always writes the text to next line. Instead you can use Write("Text") function which will write the string on same line. you can try like:
myF.Write(NamesList.ElementAt(i));
myF.Write(" ");
myF.Write(Grades.ElementAt(i));
myF.WriteLine(); // Here it will enter to new line

C#: read text file and process it

I need a program in C# which is write out
how many Eric Clapton songs played in the radios.
is there any eric clapton song which all 3 radios played.
how much time they broadcasted eric clapton songs in SUM.
The first columns contain the radio identification(1-2-3)
The second column is about the song playtime minutes
the third column is the song playtime in seconds
the last two is the performer : song
So the file looks like this:
1 5 3 Deep Purple:Bad Attitude
2 3 36 Eric Clapton:Terraplane Blues
3 2 46 Eric Clapton:Crazy Country Hop
3 3 25 Omega:Ablakok
2 4 23 Eric Clapton:Catch Me If You Can
1 3 27 Eric Clapton:Willie And The Hand Jive
3 4 33 Omega:A szamuzott
.................
And more 670 lines.
so far i get this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace radiplaytime
{
public struct Adat
{
public int rad;
public int min;
public int sec;
public Adat(string a, string b, string c)
{
rad = Convert.ToInt32(a);
min = Convert.ToInt32(b);
sec = Convert.ToInt32(c);
}
}
class Program
{
static void Main(string[] args)
{
String[] lines = File.ReadAllLines(#"...\zenek.txt");
List<Adat> adatlista = (from adat in lines
//var adatlista = from adat in lines
select new Adat(adat.Split(' ')[0],
adat.Split(' ')[1],
adat.Split(' ')[2])).ToList<Adat>();
var timesum = (from adat in adatlista
group adat by adat.rad into ertekek
select new
{
rad = ertekek.Key,
hour = (ertekek.Sum(adat => adat.min) +
ertekek.Sum(adat => adat.sec) / 60) / 60,
min = (ertekek.Sum(adat => adat.min) +
ertekek.Sum(adat => adat.sec) / 60) % 60,
sec = ertekek.Sum(adat => adat.sec) % 60,
}).ToArray();
for (int i = 0; i < timesum.Length; i++)
{
Console.WriteLine("{0}. radio: {1}:{2}:{3} playtime",
timesum[i].rad,
timesum[i].hour,
timesum[i].min,
timesum[i].sec);
}
Console.ReadKey();
}
}
}
You can define a custom class to store the values of each line. You will need to use Regex to split each line and populate your custom class. Then you can use linq to get the information you need.
public class Plays
{
public int RadioID { get; set; }
public int PlayTimeMinutes { get; set; }
public int PlayTimeSeconds { get; set; }
public string Performer { get; set; }
public string Song { get; set; }
}
So you then read your file and populate the custom Plays:
String[] lines = File.ReadAllLines(#"songs.txt");
List<Plays> plays = new List<Plays>();
foreach (string line in lines)
{
var matches = Regex.Match(line, #"^(\d+)\s(\d+)\s(\d+)\s(.+)\:(.+)$"); //this will split your line into groups
if (matches.Success)
{
Plays play = new Plays();
play.RadioID = int.Parse(matches.Groups[1].Value);
play.PlayTimeMinutes = int.Parse(matches.Groups[2].Value);
play.PlayTimeSeconds = int.Parse(matches.Groups[3].Value);
play.Performer = matches.Groups[4].Value;
play.Song = matches.Groups[5].Value;
plays.Add(play);
}
}
Now that you have your list of songs, you can use linq to get what you need:
//Get Total Eric Clapton songs played - assuming distinct songs
var ericClaptonSongsPlayed = plays.Where(x => x.Performer == "Eric Clapton").GroupBy(y => y.Song).Count();
//get eric clapton songs played on all radio stations
var radioStations = plays.Select(x => x.RadioID).Distinct();
var commonEricClaptonSong = plays.Where(x => x.Performer == "Eric Clapton").GroupBy(y => y.Song).Where(z => z.Count() == radioStations.Count());
etc.
String splitting works only if the text is really simple and doesn't have to deal with fixed length fields. It generates a lot of temporary strings as well, that can cause your program to consume many times the size of the original in RAM and harm performance due to the constant allocations and garbage collection.
Riv's answer shows how to use a Regex to parse this file. It can be improved in several ways though:
var pattern=#"^(\d+)\s(\d+)\s(\d+)\s(.+)\:(.+)$";
var regex=new Regex(pattern);
var plays = from line in File.ReadLines(filePath)
let matches=regex.Match(line)
select new Plays {
RadioID = int.Parse(matches.Groups[1].Value),
PlayTimeMinutes = int.Parse(matches.Groups[2].Value),
PlayTimeSeconds = int.Parse(matches.Groups[3].Value),
Performer = matches.Groups[4].Value,
Song = matches.Groups[5].Value
};
ReadLines returns an IEnumerable<string> instead of returning all of the lines in a buffer. This means that parsing can start immediatelly
By using a single regular expression, we don't have to rebuild the regex for each line.
No list is needed. The query returns an IEnumerable to which other LINQ operations can be applied directly.
For example :
var durations = plays.GroupBy(p=>p.RadioID)
.Select(grp=>new { RadioID=grp.Key,
Hours = grp.Sum(p=>p.PlayTimeMinutes + p.PlayTimeSecons/60)/60,)
Mins = grp.Sum(p=>p.PlayTimeMinutes + p.PlayTimeSecons/60)%60,)
Secss = grp.Sum(p=> p.PlayTimeSecons)%60)
});
A farther improvement could be to give names to the groups:
var pattern=#"^(?<station>\d+)\s(?<min>\d+)\s(?<sec>\d+)\s(?<performer>.+)\:(?<song>.+)$";
...
select new Plays {
RadioID = int.Parse(matches.Groups["station"].Value),
PlayTimeMinutes = int.Parse(matches.Groups["min"].Value),
...
};
You can also get rid of the Plays class and use a single, slightly more complex LINQ query :
var durations = from line in File.ReadLines(filePath)
let matches=regex.Match(line)
let play= new {
RadioID = int.Parse(matches.Groups["station"].Value),
Minutes = int.Parse(matches.Groups["min"].Value),
Seconds = int.Parse(matches.Groups["sec"].Value)
}
group play by play.RadioID into grp
select new { RadioID = grp.Key,
Hours = grp.Sum(p=>p.Minutes + p.Seconds/60)/60,)
Mins = grp.Sum(p=>p.Minutes + p.Seconds/60)%60,)
Secs = grp.Sum(p=> p.Seconds)%60)
};
In this case, no strings are generated for Performer and Song. That's another benefit of regular expressions. Matches and groups are just indexes into the original string. No string is generated until the .Value is read. This would reduce the RAM used in this case by about 75%.
Once you have the results, you can iterate over them :
foreach (var duration in durations)
{
Console.WriteLine("{0}. radio: {1}:{2}:{3} playtime",
duration.RadioID,
duration.Hours,
duration.Mins,
duration.Secs);
}

C# Why can't I implicitly convert type 'string' to 'System.Collections.Generic.List<int>'?

I am trying to figure out how to solve the error as stated in the title, which occurs on the bold line within this snippet:
while (textIn.Peek() != -1)
{
string row = textIn.ReadLine();
string[] columns = row.Split('|');
StudentClass studentList = new StudentClass();
studentList.Name = columns[0];
**studentList.Scores = columns[1];**
students.Add(studentList);
}
The previous line of code loads the names just fine since it is not a List within the class I have created, but "Scores" is within a list, however. What modifications would I need to do? These values are supposed to be displayed within a textbox from a text file upon loading the application.
Here is the class in which "Scores" is in (I have highlighted it):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyNameSpace
{
//set the class to public
public class StudentClass
{
public StudentClass()
{
this.Scores = new List<int>();
}
public StudentClass (string Name, List<int> Scores)
{
this.Name = Name;
this.Scores = Scores;
}
public string Name
{ get;
set;
}
//initializes the scores
**public List<int> Scores
{ get;
set;
}**
public override string ToString()
{
string names = this.Name;
foreach (int myScore in Scores)
{ names += "|" + myScore.ToString();
}
return names;
}
public int GetScoreTotal()
{
int sum = 0;
foreach (int score in Scores)
{ sum += score;
}
return sum;
}
public int GetScoreCount()
{ return Scores.Count;
}
public void addScore(int Score)
{
Scores.Add(Score);
}
}
}
You can't just assign a string containing a sequence of numbers to a property of type List<int>.
You need to split the string into seperate numbers, then parse these substrings to get the integers they represent.
E.g.
var text = "1 2 3 4 5 6";
var numerals = text.Split(' ');
var numbers = numerals.Select(x => int.Parse(x)).ToList();
I.e. in your code replace:
studentList.Scores = columns[1];
with:
studentList.Scores = columns[1].Split(' ').Select(int.Parse).ToList();
(Or your own multi-line, more readable/debugable equivalent.)
You'll need to modify the parameter passed to Split() according to how the scores are formatted in your column.
You'll also need to add using System.Linq; at the top if you don't already have it.
As far as the question goes, how would the compiler ever know how to convert the string to a list, when there could be so many string representations of a list. If it was to do this it would be an incredibly slow operation.
Fix
To fix your code you could replace your loop with this.
while (textIn.Peek() != -1)
{
string row = textIn.ReadLine();
StudentClass studentList = new StudentClass();
int index = row.IndexOf("|");
//checking that there were some scores
if (index < 0) {
studentList.Name = row;
continue;
}
studentList.Name = row.Substring(0, index);
studentList.Scores = row.Substring(index + 1).Split('|').Select(int.Parse).ToList();
students.Add(studentList);
}
There are however a number of problems even with this fix.
For one if you were to add another list delimited by '|' it would become increasingly hard for you to parse using this kind of approach.
I suggest instead that you look at serializing your class(es) with something a little more powerful and generic like Json.Net.
Hope this helps.

How to count occurences of number stored in file containing multiple delimeters?

This is my input store in file:
50|Carbon|Mercury|P:4;P:00;P:1
90|Oxygen|Mars|P:10;P:4;P:00
90|Serium|Jupiter|P:4;P:16;P:10
85|Hydrogen|Saturn|P:00;P:10;P:4
Now i will take my first row P:4 and then next P:00 and then next like wise and want to count occurence in every other row so expected output will be:
P:4 3(found in 2nd row,3rd row,4th row(last cell))
P:00 2 (found on 2nd row,4th row)
P:1 0 (no occurences are there so)
P:10 1
P:16 0
etc.....
Like wise i would like to print occurence of each and every proportion.
So far i am successfull in splitting row by row and storing in my class file object like this:
public class Planets
{
//My rest fields
public string ProportionConcat { get; set; }
public List<proportion> proportion { get; set; }
}
public class proportion
{
public int Number { get; set; }
}
I have already filled my planet object like below and Finally my List of planet object data is like this:
List<Planets> Planets = new List<Planets>();
Planets[0]:
{
Number:50
name: Carbon
object:Mercury
ProportionConcat:P:4;P:00;P:1
proportion[0]:
{
Number:4
},
proportion[1]:
{
Number:00
},
proportion[2]:
{
Number:1
}
}
Etc...
I know i can loop through and perform search and count but then 2 to 3 loops will be required and code will be little messy so i want some better code to perform this.
Now how do i search each and count every other proportion in my planet List object??
Well, if you have parsed proportions, you can create new struct for output data:
// Class to storage result
public class Values
{
public int Count; // count of proportion entry.
public readonly HashSet<int> Rows = new HashSet<int>(); //list with rows numbers.
/// <summary> Add new proportion</summary>
/// <param name="rowNumber">Number of row, where proportion entries</param>
public void Increment(int rowNumber)
{
++Count; // increase count of proportions entries
Rows.Add(rowNumber); // add number of row, where proportion entry
}
}
And use this code to fill it. I'm not sure it's "messy" and don't see necessity to complicate the code with LINQ. What do you think about it?
var result = new Dictionary<int, Values>(); // create dictionary, where we will storage our results. keys is proportion. values - information about how often this proportion entries and rows, where this proportion entry
for (var i = 0; i < Planets.Count; i++) // we use for instead of foreach for finding row number. i == row number
{
var planet = Planets[i];
foreach (var proportion in planet.proportion)
{
if (!result.ContainsKey(proportion.Number)) // if our result dictionary doesn't contain proportion
result.Add(proportion.Number, new Values()); // we add it to dictionary and initialize our result class for this proportion
result[proportion.Number].Increment(i); // increment count of entries and add row number
}
}
You can use var count = Regex.Matches(lineString, input).Count;. Try this example
var list = new List<string>
{
"50|Carbon|Mercury|P:4;P:00;P:1",
"90|Oxygen|Mars|P:10;P:4;P:00",
"90|Serium|Jupiter|P:4;P:16;P:10",
"85|Hydrogen|Saturn|P:00;P:10;P:4"
};
int totalCount;
var result = CountWords(list, "P:4", out totalCount);
Console.WriteLine("Total Found: {0}", totalCount);
foreach (var foundWords in result)
{
Console.WriteLine(foundWords);
}
public class FoundWords
{
public string LineNumber { get; set; }
public int Found { get; set; }
}
private List<FoundWords> CountWords(List<string> words, string input, out int total)
{
total = 0;
int[] index = {0};
var result = new List<FoundWords>();
foreach (var f in words.Select(word => new FoundWords {Found = Regex.Matches(word, input).Count, LineNumber = "Line Number: " + index[0] + 1}))
{
result.Add(f);
total += f.Found;
index[0]++;
}
return result;
}
I made a DotNetFiddle for you here: https://dotnetfiddle.net/z9QwmD
string raw =
#"50|Carbon|Mercury|P:4;P:00;P:1
90|Oxygen|Mars|P:10;P:4;P:00
90|Serium|Jupiter|P:4;P:16;P:10
85|Hydrogen|Saturn|P:00;P:10;P:4";
string[] splits = raw.Split(
new string[] { "|", ";", "\n" },
StringSplitOptions.None
);
foreach (string p in splits.Where(s => s.ToUpper().StartsWith(("P:"))).Distinct())
{
Console.WriteLine(
string.Format("{0} - {1}",
p,
splits.Count(s => s.ToUpper() == p.ToUpper())
)
);
}
Basically, you can use .Split to split on multiple delimiters at once, it's pretty straightforward. After that, everything is gravy :).
Obviously my code simply outputs the results to the console, but that part is fairly easy to change. Let me know if there's anything you didn't understand.

Splitting data from a text file into parallel arrays

My professor gave the class an example of C# that can be used to split data from a text file. I am trying to use it for a project that involves splitting the contents of a txt. file into 4 arrays or fields. Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
class Program
{
static void Main()
{
int i = 0;
foreach (string line in File.ReadAllLines("census.txt"))
{
string[] parts = line.Split(',');
foreach (string part in parts)
{
Console.WriteLine("{0}",
part);
}
i++;
}
}
}
Here is census.txt:
21,f, s, 14
41,f, m, 22
12, m, s, 12
11, f, s, 8
29, m, m, 4
6, m, s, 12
9, f, s, 2
30, f, s, 1
It's supposed to be hypothetical census data going by age, gender, marital status, and district. The output I keep getting is each of those numbers or chars in a single line like so:
21
f
s
14
41
f
m
22
and so on.
I think it means it's working but I'd like to know how to use this for entering into 4 parallel arrays. I would also to know more about splitting it into 4 fields, structs, or classes. The next part of the project involves counting every time a certain age number or district number appears and that will involve a lot of arrays.
I would extend irsog's answer a bit:
Use a class instead of a structure
Use properties instead of fields
Use Gender and MaritalStatus enums instead of plain strings
Code:
public class Person
{
public int Age { get; set; }
public MaritalStatus MaritalStatus { get; set; }
public Gender Gender { get; set; }
public int District { get; set; }
}
public enum MaritalStatus
{
Single, Married
}
public enum Gender
{
Male, Female
}
And usage:
var people = new List<Person>();
foreach (string line in File.ReadAllLines("Input.txt"))
{
string[] parts = line.Split(',');
people.Add(new Person() {
Age = int.Parse(parts[0]),
MaritalStatus = parts[1] == "s" ? MaritalStatus.Single : MaritalStatus.Married,
Gender = parts[2] == "m" ? Gender.Male : Gender.Female,
District = int.Parse(parts[3])
});
}
This is old thread, but as google shows it among first few pages I decided to send my comment. I strongly advise against given txt file format, because it is not error proof. If census.txt is not guaranteed to be ideal and especially if it is supposed to be created by some third party (user, administrator, whoever) then I strongly recommend records to be ended with some symbol, like this:
21,f, s, 14;
41,f, m, 22;
then first thing what we do - we get array of records, like this:
string[] lines = text.split(';');
then simply split again - this time to get record elements.
foreach (string record in lines)
{
string[] fields = record.split(',');
}
This way it is not only easier to read records/fields, but also you can easily check consistency of file, ignore errors (empty records), check number of fields in each records and etc.
A generic list (as used in the other 2 current answers here) is the best way to go. However, if you need to have the data in arrays (as your previous question seems to indicate), then you can modify your professor's code like this:
C#
int[] districtDataD = new int[900];
string[] districtDataG = new string[900];
string[] districtDataM = new string[900];
int[] districtDataA = new int[900];
int i = 0;
foreach (string line in File.ReadAllLines("census.txt"))
{
string[] parts = line.Split(',');
districtDataD[i] = int.Parse(parts[0]);
districtDataS[i] = parts[1];
districtDataM[i] = parts[2];
districtDataA[i] = int.Parse(parts[3]);
i++;
}
VB.NET (Since your original question was tagged with VB.NET):
Dim districtDataD() As New Integer(900)
Dim districtDataS() As New String(900)
Dim distrcitDataM() As New String(900)
Dim districtDataA() As New Integer(900)
Dim i As Integer = 0
For Each Dim line As String In File.ReadAllLines("census.txt")
Dim string() As parts = line.Split(',')
districtDataD(i) = Integer.Parse(parts(0))
districtDataS(i) = parts(1)
districtDataM(i) = parts(2)
districtDataA(i) = Integer.Parse(parts(3))
i++
Next
You could also use a struct or class and have one array that holds that object, but it looks like you're professor wants you to use 4 separate arrays. If you can use one, you can simply declare the array like this, for example:
C#
Person[] districtData = new Person[900];
VB.NET
Dim districtData() As New Person(900)
Then you could do this inside the split logic (note that if, say Distric and Age are integers in your object you'll have to cast or parse them as I show below):
C#
districtData[i] = new Person() { District = int.Parse(parts[0]), Gender = parts[1], MaritalStatus = parts[2], Age = int.Parse(parts[3]) };
VB.NET
districtData[i] = new Person() With { .District = Integer.Parse(parts[0]), .Gender = parts[1], .MaritalStatus = parts[2], .Age = Integer.Parse(parts[3]) }
There's a risk with this code that if you have more than 900 lines of data, you will get an index out of range exception. One way to avoid this would be to modify the code I put above with a while loop that checks the bounds of the target array(s) or the the number of lines haven't been exceed, like this:
C#
string[] lines = File.ReadAllLines("census.txt");
int i = 0;
while (i < 900 && i < parts.Length)
{
// split logic goes here
}
VB.NET
Dim lines As String() = File.ReadAllLines("census.txt")
Dim i As Integer = 0
While (i < 900 AndAlso i < lines.Length)
' split logic goes here
End While
I haven't tested the code, but this will hopefully help you if you must use arrays.
You can Make a structure for required information:
public struct Info
{
public int Age;
public string gender;
public string status;
public int district;
}
and inset data to your structure list:
List<Info> info = new List<Info>();
foreach (string line in File.ReadAllLines("census.txt"))
{
string[] parts = line.Split(',');
info.Add(new Info() {Age=int.Parse(parts[0]), gender=parts[1], status=parts[2], district=int.Parse(parts[3]) });
}
Now yo have a list of person information.

Categories