Posts

Showing posts with the label linq

Is there a shorter, better and optimised way to fill this list from SQL database

Is there a shorter, better and optimised way to fill this list from SQL database I got this code and it works without problems. But i sense there is much better way to do this. namespace Repositories { public class AuthorRepository : IAuthorRepository { public List<Author> GetAllFromRepo() { using (AppContext myDB = new AppContext()) { List<Author> authorsFromRepo = new List<Author>(); foreach (var item in myDB.Authors) { authorsFromRepo.Add(new Author() { Books = new List<Book>(), ID = item.ID, FirstName = item.FirstName, LastName = item.LastName }); } return authorsFromRepo.ToList(); } ...

C# Lambda expressions with Classes

C# Lambda expressions with Classes I am reading a csv with a list of students - Name, Surname, ClassLeader, Grade,Subject, Score. I want to add a new student if he doesn't exist or only add the Subject and Score if the student exists in the list. Code below: class School { private int Grades = new int[5] { 8, 9, 10, 11, 12 }; public List<Student> Students = new List<Student>(); private HashSet<string> AllSubjects = new HashSet<string>(); public School() { } public void CreateStudents() { List<string> storedCSVData = CSVHelper.ReadCSV(); //int index = 0; foreach(string lineItem in storedCSVData) { //index++; //if ((index % 6) != 0) // continue; string fullName = lineItem[0] + " " + lineItem[1]; int i = Students.IndexOf(x => ...

How to use list.where function with the objects getting casted before getting an IEnumerable

How to use list.where function with the objects getting casted before getting an IEnumerable My classes are like this public interface ICar { CarModel GetCarModel(); } public class Honda: ICar { CarModel GetCarModel() { return CarModel.Honda; } } I have a list of ICars defined like this: ICars List<ICar> cars; I am looking to extract a IEnumerable of all cars of type Honda using the Where clause and casted to Honda and not to ICar. How do I do this? Is this possible? BTW more idiomatic C# would use a property not a method: public CarModel CarModel => CarModel.Honda; and it would need to be public to satisfy the interface. – Ian Mercer Jul 1 at 10:53 public CarModel CarModel => CarModel.Honda; public Not, that type design like this leads to "double-typing". Noting p...