I am attemping to read a text file in the format of
(The # at end is just the number of classes they're in, but I dont save the course name with the fac/students class)
Course Biology
Faculty Taylor Nate 0
Student Doe John 3
Student Sean Big 0
Course Art
Faculty Leasure Dan 1
The first input should be a course, followed by the faculty and students of the specific course. The Course class should contain a collection of faculty members and a collection of students.
I have been able to put each course/student/faculty into their respective class, but I am having trouble visualizing a way to add the students/faculty to the course.
My current idea putting the data into their respective classes would be to keep the current index of the course- therefore I have it saved as
courses[currentCourse++]
so when I parse the next line, (being a faculty/student) I already know what the course index should be.
using (StreamReader reader = new StreamReader(fileName))
{
while (!reader.EndOfStream)
{
lineCounter++;
line = reader.ReadLine();
string[] words = line.Split(' ');
Console.WriteLine(words[0]);
if (words[0] == "Course")
{
string nameOfCourse = words[1];
courses[currentCourse++] = new Course
{
Name = nameOfCourse
};
}
if (words[0] == "Faculty")
{
string firstName = words[1];
string lastName = words[2];
string numOfClasses = words[3];
faculty[currentFaculty++] = new Faculty
{
FirstName = firstName,
LastName = lastName,
NumOfClasses = numOfClasses,
};
}
if (words[0] == "Student")
{
string firstName = words[1];
string lastName = words[2];
string numOfClasses = words[3];
students[currentStudent++] = new Student
{
FirstName = firstName,
LastName = lastName,
NumOfClasses = numOfClasses,
};
}
I know the problem lies in the courses class itself- but i'm not sure the terminology to add a class to another class.
public class Course
{
public override string ToString()
{
return $"{Name}";
}
public string Name { get; set; }
}
public class Student
{
public override string ToString()
{
return $"{FirstName} {LastName} {NumOfClasses}";
}
public string FirstName { get; set; } = string.Empty;
public string LastName { get; set; } = string.Empty;
public string NumOfClasses { get; set; } = string.Empty;
}
Thanks for reading!
You want to add a collection of Student and Faculty to the course class, correct? You can do so like this by simply adding a List<T> to your Course class and then initializing it in a constructor.
public class Course
{
public override string ToString()
{
return $"{Name}";
}
public string Name { get; set; }
public List<Student> Students { get; set; }
public List<Faculty> FacultyMems { get; set; }
public Course()
{
Students = new List<Student>();
FacultyMems = new List<Faculty>();
}
}
And in your using block, you can add each student/faculty to the course as so:
if (words[0] == "Course")
{
string nameOfCourse = words[1];
currentCourse++;
courses[currentCourse] = new Course
{
Name = nameOfCourse
};
}
if (words[0] == "Faculty")
{
string firstName = words[1];
string lastName = words[2];
string numOfClasses = words[3];
courses[currentCourse].FacultyMems.Add(new Faculty
{
FirstName = firstName,
LastName = lastName,
NumOfClasses = numOfClasses,
});
}
if (words[0] == "Student")
{
string firstName = words[1];
string lastName = words[2];
string numOfClasses = words[3];
courses[currentCourse].Students.Add(new Student
{
FirstName = firstName,
LastName = lastName,
NumOfClasses = numOfClasses,
});
}
With this, each time you encounter "Course" your course list will add a new item and then you can append students/faculty/etc when those values occur.
This can be simplified even further but the concept is there for you to follow. Hope this helps.
If I'm understanding you correctly, you want your courses to have a list of faculty and students?
public class Course
{
public override string ToString()
{
return $"{Name}";
}
public string Name { get; set; }
public List<Student> Students { get; set; }
public List<Faculty> FacultyMembers {get; set;}
}
Just be sure to initialize the Lists before trying to add things to them otherwise you'll get a null ref exception.
Related
Need help with a better pratices question
I have an azure function that brings data form differents APIs and match them toguether to create a final csv report. I have a poblation of 60k-100k and 30 columns
For the sake of the explanation, I'm going to use a small School example.
public Student {
string Grade {get; set;}
Name LegName {get; set;}
string FatherName {get; set;}
string TeacherId {get; set;}
string SchoolId {get; set;}
}
public Name {
string FirstName {get; set;}
string LastName {get; set;}
}
Before constructing the report, I create two Dictionary with <Id, Name> from two APIs that expose Schools and Teachers information. And of course, a list of Student that comes from the Student APIs. I have no control of this trhee APIs, design, data quality, nothing.
Now, when I have all the data, I start to create the report.
string GenerateTXT(Dictionary<string, string> schools, Dictionary<string, string> teachers, Student students){
StringBuilder content = new StringBuilder();
foreach(var student in students){
content.Append($"{student.Grade}\t");
content.Append($"{student.LegName.FirstName}\t");
content.Append($"{student.LegName.LastName}\t");
content.Append($"{schools.TryGetValue(student.TeacherId)}\t");
content.Append($"{teachers.TryGetValue(student.SchoolId)}t";
content.Append($"{student.FatherNme}\t");
content.AppendLine();
}
return content.ToString();
}
Now here comes the problem. I started noticing data quality issues so the function started throwing exceptions. For example, students who do not have a valid school or teacher, or a student who does not have a name. I tried to solve expected scenarios and exception handling.
string GenerateTXT(Dictionary<string, string> schools, Dictionary<string, string> teachers, Student students){
StringBuilder content = new StringBuilder();
var value = string.Empty;
foreach(var student in students){
try {
content.Append($"{student.Grade}\t");
content.Append($"{student.LegName.FirstName}\t");
content.Append($"{student.LegName.LastName}\t");
if(teachers.TryGetValue(student.TeacherId))
content.Append($"{teachers[student.TeacherId]}\t");
else
content.Append($"\t");
if(schools.TryGetValue(student.SchoolId))
content.Append($"{schools[student.SchoolId]}\t");
else
content.Append($"\t");
content.Append($"{student.FatherNme}\t");
content.AppendLine();
}
catch(Exception ex) {
log.Error($"Error reading worker {student.FirstName}");
}
}
return content.ToString();
}
The problem with this is that when an unexpected error happens, I stop reading the next columns of data that maybe I have and instead jump to the next worker. Therefore, if a student for some random reason does not have a name, that row in the report will only have the grade, and nothing else, but I actually had the rest of the values. So here comes the question. I could put a try catch on each column, but remember that my real scenario has like 30 columns and could be more... so I think it's a really bad solution. Is there a pattern to solve this in a better way?
Thanks in advance!
So the first bit of advice I am going to give you is to use CsvHelper. This is a tried and true library as it handles all those edge cases you will never think of. So, saying that, give this a shot:
public class Student
{
public string Grade { get; set; }
public Name LegName { get; set; }
public string FatherName { get; set; }
public string TeacherId { get; set; }
public string SchoolId { get; set; }
}
public class Name
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class NormalizedData
{
public string Grade { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string School { get; set; }
public string Teacher { get; set; }
public string FatherName { get; set; }
}
static void GenerateCSVData(CsvHelper.CsvWriter csv, Dictionary<string, string> schools,
Dictionary<string, string> teachers, Student[] students)
{
var normalizedData = students.Select(x => new NormalizedData
{
Grade = x.Grade,
FatherName = x.FatherName,
FirstName = x.LegName?.FirstName, // sanity check incase LegName is null
LastName = x.LegName?.LastName, // ...
School = schools.ContainsKey(x.SchoolId ?? string.Empty) ? schools[x.SchoolId] : null,
Teacher = teachers.ContainsKey(x.TeacherId ?? string.Empty) ? teachers[x.TeacherId] : null
});
csv.WriteRecords(normalizedData);
}
private static string GenerateStringCSVData(Dictionary<string, string> schools,
Dictionary<string, string> teachers, Student[] students)
{
using(var ms = new MemoryStream())
{
using(var sr = new StreamWriter(ms, leaveOpen: true))
using (var csv = new CsvHelper.CsvWriter(sr,
new CsvConfiguration(CultureInfo.InvariantCulture)
{
Delimiter = ",", // change this to "\t" if you want to use tabs
Encoding = Encoding.UTF8
}))
{
GenerateCSVData(csv, schools, teachers, students);
}
ms.Position = 0;
return Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Length);
}
}
private static int Main(string[] args)
{
var teachers = new Dictionary<string, string>
{
{ "j123", "Jimmy Carter" },
{ "r334", "Ronald Reagan" },
{ "g477", "George Bush" }
};
var schools = new Dictionary<string, string>
{
{ "s123", "Jimmy Carter University" },
{ "s334", "Ronald Reagan University" },
{ "s477", "George Bush University" }
};
var students = new Student[]
{
new Student
{
FatherName = "Bob Jimmy",
SchoolId = "s477",
Grade = "5",
LegName = new Name{ FirstName = "Apple", LastName = "Jimmy" },
TeacherId = "r334"
},
new Student
{
FatherName = "Jim Bobby",
SchoolId = null, // intentional
Grade = "", // intentional
LegName = null, // intentional
TeacherId = "invalid id" // intentional
},
new Student
{
FatherName = "Mike Michael",
SchoolId = "s123",
Grade = "12",
LegName = new Name{ FirstName = "Peach", LastName = "Michael" },
TeacherId = "g477"
},
};
var stringData = GenerateStringCSVData(schools, teachers, students);
return 0;
}
This outputs:
Grade,FirstName,LastName,School,Teacher,FatherName
5,Apple,Jimmy,George Bush University,Ronald Reagan,Bob Jimmy
,,,,,Jim Bobby
12,Peach,Michael,Jimmy Carter University,George Bush,Mike Michael
So, you can see, one of the students has invalid data in it, but it recovers just fine by placing blank data instead of crashing or throwing exceptions.
Now I haven't seen your original data, so there may be more tweaks you have to make to this to cover all edge cases, but it will be a lot easier to tweak this when using CsvHelper as your writer.
Query result from search
Greetings, i am new using linq syntax and i need help translating the query in the picture to get the needed result in c#. I have two questions. First of all How do i do inner joins using linq syntax in c# in order to get the desired result showed in the image. Second, in order to show the data obtained from the query, do i need to create a ViewModel that has 3 ViewModels from the different tables used in the query search?
Thank you so very much for your help.
As levelonehuman said, linq is designed to query data. lets say you have a couple classes:
public class Person
{
public static class Factory
{
private static int currentId = 0;
public static Person Create(string firstName, string lastName, string phoneNumber, int companyId)
{
return new Person()
{
Id = ++currentId,
FirstName = firstName,
LastName = lastName,
PhoneNumber = phoneNumber,
CompanyId = companyId
};
}
}
public int Id { get; private set; }
public string FirstName { get; private set; }
public string LastName { get; private set; }
public string PhoneNumber { get; private set; }
public int CompanyId { get; private set; }
}
public class Company
{
public static class Factory
{
private static int companyId=0;
public static Company Create(string name, string city, string state, string phoneNumber)
{
return new Company()
{
Id = ++ companyId,
City = city,
State = state,
Name = name,
PhoneNumber = phoneNumber
};
}
}
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PhoneNumber { get; set; }
}
and then you want to see only people from a certain area code you could do something like this:
class Program
{
static void Main(string[] args)
{
var companies = new[]
{
Company.Factory.Create("ABC", "Indianapolis", "In", "(317) 333 5555"),
Company.Factory.Create("Def", "Bloominton", "In", "(812) 333 5555"),
};
var people = new[]
{
Person.Factory.Create("Jane", "Doe", "(317) 555 7565", 1),
Person.Factory.Create("Paul", "Smith", "(812) 555 7565", 2),
Person.Factory.Create("Sean", "Jackson", "(317) 555 7565", 2),
Person.Factory.Create("Jenny", "Gump", "(812) 555 7565", 1)
};
var peopleFromIndianapolis =
(
from company in companies
join person in people on company.Id equals person.CompanyId
where person.PhoneNumber.StartsWith("(317)")
orderby person.LastName, person.FirstName
select new
{
person.FirstName,
person.LastName,
company.Name
}
).ToList();
foreach (var person in peopleFromIndianapolis)
{
Console.WriteLine($"PersonName: {person.LastName}, {person.FirstName} - Company:{person.Name}");
}
}
}
Hope this helps!
I have the following columns in Entity Framework Code first approach:
public string LastName { get; set; }
public string FirstName { get; set; }
And I combine them into a full name:
public string FullName
{
get { return LastName + " " + FirstName; }
}
I don't even know if it's possible, but how I can generate a setter for this in order to send the values from the fullname to the other 2 columns when selecting it from e.g a dropdown list?
Say you would do a FullName.Split(' '); getting an array of names. It's all good when first and last names are single word. But how about John Billy Doe? Where does the LastName end and the FirstName begin?
Instead, you could use a different separator, like a comma: John, Billy Doe.
That way, doing a FullName.Split(','); would yield the correct Last Name and First Name.
public string FullName
{
get
{
return LastName + ", " + FirstName;
}
set
{
string[] names = value.Split(", ");
LastName = names[0];
FirstName = names[1];
}
}
EDIT: Of course, some validation is required for the value, but it's pretty hard to type code on the Android app (as I am doing). So, unless you need help with that, I leave it up to you.
The simpler approach would be to split on the first space you see, but it would break if anyone has a first or last name with a space in it. Broken first-names are rare, but last-names with spaces are common, e.g. "Jean-Claude Van Damme".
public String FullName {
set {
Int32 spaceIdx = value.IndexOf(" ");
if( spaceIdx == -1 ) {
this.FirstName = value;
this.LastName = "";
}
else
{
this.FirstName = value.Substring(0, spaceIdx);
this.LastName = value.Substring(spaceIdx + 1);
}
}
}
A better approach is to identify the names uniquely in your system and use that from your name-dropdown. Assuming this is ASP.NET MVC:
public class YourViewModel {
public IEnumerable<SelectListItem> Names { get; set; }
public Int32 SelectedNameByPersonId { get; set; }
}
In your controller:
public IActionResult YourAction() {
List<SelectListItem> names = db.People.Select( dbPerson => new SelectListItem() {
Text = dbPerson.FirstName + " " + dbPerson.LastName,
Value = dbPerson.Id.ToString()
} ).ToList(); // ToList so the DB is only queried once
return this.View( new YourViewModel() { Names = names } );
}
[HttpPost]
public IActionResult YourAction(YourViewModel model) {
DBPerson dbPerson = db.People.GetPerson( model.SelectedNameByPersonId );
// do stuff with person
}
In your view (aspx syntax):
<%= Html.DropDownFor( m => m.SelectNameByPersonId, this.Model.Names ) %>
I'm not exactly sure what you are asking, but I think this might help(plus input error handling).
public string LastName { get; set; }
public string FirstName { get; set; }
public string FullName
{
get
{
return LastName + " " FirstName;
}
series
{
var nameParts = value.Split(' ');
LastName = string.IsNullOrEmpty(nameParts[0]) ? string.Empty : nameParts[0];
FirstName = string.IsNullOrEmpty(nameParts[1]) ? string.Empty : nameParts[1];
}
}
I have tried for some workaround. Please try this and let me know of it works.
public string LastName { get; set; }
public string FirstName { get; set; }
[NotMapped] //This will make sure that entity framework will not map this to a new column
public string FullName
{
get { return LastName + " " + FirstName; }
// Here comes your desired setter method.
set
{
string[] str = value.Split(' ');
if (str.Length == 2)
{
FirstName = str[1];
LastName = str[0];
}
else if (str.Length >= 0 && value.Length > 0)
{
LastName = str[0];
}
else
throw new Exception("Invalid name");
}
}
I'm creating an WindowsForms application that is using a list of persons with 4 parameters (ID, Name, Surname, Permissions):
public List<Osoba> ListaOsoba()
{
Osoba nr1 = new Osoba(1, "Name", "Surname", Permissions.Administrator);
Osoba nr2 = new Osoba(2, "Name2", "Surname2", Permissions.Użytkownik);
Osoba nr3 = new Osoba(3, "Name3", "Surname3", Permissions.Użytkownik);
listaOsób.Add(nr1);
listaOsób.Add(nr2);
listaOsób.Add(nr3);
return listaOsób;
}
I would like to post all those Parameters to CheckedListBox, but show only name and surname to the user. The ID and Permissions should be hidden, but they need to exist, because I want to use them later.
Every help will be appreciated.
public static bool CheckBoxListPopulate(CheckBoxList CbList, IList<T> liSource, string TextFiled, string ValueField)
{
try
{
CbList.Items.Clear();
if (liSource.Count > 0)
{
CbList.DataSource = liSource;
CbList.DataTextField = TextFiled;
CbList.DataValueField = ValueField;
CbList.DataBind();
return true;
}
else { return false; }
}
catch (Exception ex)
{ throw ex; }
finally
{
}
}
here Cb list is the control name and
List item Ilist is the list source name
Text field (should be concatination ) ="Name" + "Surname"
Value field will be Hidden it can be "1,2,3"
so only Text field will be visible to user
To bind only name and surname to checkedboxlist first store name and surname together and then try this:
NameS = "Name" + "Surname";
((ListBox)checkedListBox).DataSource = listaOsób;
((ListBox)checkedListBox).DisplayMember = "NameS";
try this, here you have to make arbitrary compound properties for display and value member like DisplayName and HiddenId and then you can easily bound with checkedlistbox.
public class Osoba
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Permissions Permission { get; set; }
public string DisplayName { get; set; }
public string HiddenId { get; set; }
public Osoba()
{ }
public Osoba(int id, string fname, string lname, Permissions p)
{
Id = id;
FirstName = fname;
LastName = lname;
Permission = p;
DisplayName = FirstName + " " + LastName;
HiddenId = Id + "_" + Permission.GetHashCode();
}
public void ListaOsoba()
{
List<Osoba> objList = new List<Osoba>();
Osoba nr1 = new Osoba(1, "Name", "Surname", Permissions.Administrator);
Osoba nr2 = new Osoba(2, "Name2", "Surname2", Permissions.Uzytkownik);
Osoba nr3 = new Osoba(3, "Name3", "Surname3", Permissions.Uzytkownik);
objList.Add(nr1);
objList.Add(nr2);
objList.Add(nr3);
((ListBox)checkedListBox1).DataSource = objList;
((ListBox)checkedListBox1).DisplayMember = "DisplayName";
((ListBox)checkedListBox1).ValueMember = "HiddenId";
MessageBox.Show(((ListBox)checkedListBox1).Text);
MessageBox.Show(((ListBox)checkedListBox1).SelectedValue.ToString());
}
}
public enum Permissions
{
Administrator,
Uzytkownik
}
I had a similar thing with SQL. I returned many columns, but only wanted one to show.
Anyway
ArrayList arr = new ArrayList();
foreach (object o in ListaOsoba)
{
arr.Items.Add(o[1].ToString()+" "+o[2].ToString());
}
foreach (var item in arr)
{
chkNames.Items.Add(arr.ToString()); //chkNames is your CheckListBox
}
Then later when querying which ID and such goes where, loop through you original list, and see who was ticked based on the name and surname combo, find the ID related to that person and you should be sorted
I have the code below. I'd like to convert all items in this list to uppercase.
Is there a way to do this in Linq ?
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
public class MyClass
{
List<Person> myList = new List<Person>{
new Person { FirstName = "Aaa", LastName = "BBB", Age = 2 },
new Person{ FirstName = "Deé", LastName = "ève", Age = 3 }
};
}
Update
I don't want to loop or go field by field. Is there a way by reflection to uppercase the value for each property?
Why would you like to use LINQ?
Use List<T>.ForEach:
myList.ForEach(z =>
{
z.FirstName = z.FirstName.ToUpper();
z.LastName = z.LastName.ToUpper();
});
EDIT: no idea why you want to do this by reflection (I wouldn't do this personally...), but here's some code that'll uppercase all properties that return a string. Do note that it's far from being perfect, but it's a base for you in case you really want to use reflection...:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
public static class MyHelper
{
public static void UppercaseClassFields<T>(T theInstance)
{
if (theInstance == null)
{
throw new ArgumentNullException();
}
foreach (var property in theInstance.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
var theValue = property.GetValue(theInstance, null);
if (theValue is string)
{
property.SetValue(theInstance, ((string)theValue).ToUpper(), null);
}
}
}
public static void UppercaseClassFields<T>(IEnumerable<T> theInstance)
{
if (theInstance == null)
{
throw new ArgumentNullException();
}
foreach (var theItem in theInstance)
{
UppercaseClassFields(theItem);
}
}
}
public class Program
{
private static void Main(string[] args)
{
List<Person> myList = new List<Person>{
new Person { FirstName = "Aaa", LastName = "BBB", Age = 2 },
new Person{ FirstName = "Deé", LastName = "ève", Age = 3 }
};
MyHelper.UppercaseClassFields<Person>(myList);
Console.ReadLine();
}
}
LINQ does not provide any facilities to update underlying data. Using LINQ, you can create a new list from an existing one:
// I would say this is overkill since creates a new object instances and
// does ToList()
var updatedItems = myList.Select(p => new Person
{
FirstName = p.FirstName.ToUpper(),
LastName = p.LastName.ToUpper(),
Age = p.Age
})
.ToList();
If using LINQ is not principal, I would suggest using a foreach loop.
UPDATE:
Why you need such solution? Only one way of doing this in generic manner - reflection.
the Easiest approach will be to use ConvertAll:
myList = myList.ConvertAll(d => d.ToUpper());
Not too much different than ForEach loops the original list whereas ConvertAll creates a new one which you need to reassign.
var people = new List<Person> {
new Person { FirstName = "Aaa", LastName = "BBB", Age = 2 },
new Person{ FirstName = "Deé", LastName = "ève", Age = 3 }
};
people = people.ConvertAll(m => new Person
{
FirstName = m.FirstName?.ToUpper(),
LastName = m.LastName?.ToUpper(),
Age = m.Age
});
to answer your update
I don't want to loop or go field by field. Is there a way by
reflection to uppercase the value for each property?
if you don't want to loop or go field by field.
you could use property on the class to give you the Uppercase like so
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string FirstNameUpperCase => FirstName.ToUpper();
public string LastNameUpperCase => LastName.ToUpper();
}
or you could use back field like so
public class Person
{
private string _firstName;
public string FirstName {
get => _firstName.ToUpper();
set => _firstName = value;
}
private string _lastName;
public string LastName {
get => _lastName.ToUpper();
set => _lastName = value;
}
public int Age { get; set; }
}
You can only really use linq to provide a list of new objects
var upperList = myList.Select(p=> new Person {
FirstName = (p.FirstName == null) ? null : p.FirstName.ToUpper(),
LastName = (p.LastName == null) ? null : p.LastName.ToUpper(),
Age = p.Age
}).ToList();
p.lastname.ToString().ToUpper().Contains(TextString)