I have to make a connection between Students,classes, and year like this: One year can have 1 or more classes and 1 class can have 1 or more students.
I made this with a generic list. The problem is that I have to get the information from one .txt file and I don't know how to do it.
My file is like this:
(Year,Class,Name,Surname,Average).
1 314 George Andrew 8
2 324 Popescu Andrei 9
2 323 Andreescu Bogdan 10
3 332 Marin Darius 9
3 332 Constantin Roxana 10
Code:
public class Student
{
public string Name { get; set; }
public string Surname { get; set; }
public int Average { get; set; }
}
}
public class Grupa
{
public int Name { get; set; }
public List<Student> SetStudent { get; set; }
public Grupa()
{
SetStudent = new List<Student>();
}
public void Print()
{
//Console.WriteLine("Grupa: " + this.Name);
Console.WriteLine("Studentii din grupa: ");
foreach (Student s in this.SetStudent)
{
Console.WriteLine(" " + s.Name+ " " + s.Surname + " --- " + s.Average+"\n");
}
}
}
public class An
{
public int Anul { get; set; }
public List<Grupa> SetGrupa { get; set; }
public An()
{
SetGrupa = new List<Grupa>();
}
public void Print()
{
Console.WriteLine("Anul: " + this.Anul);
Console.WriteLine("Grupele din acest an: ");
foreach (Grupa g in this.SetGrupa)
{
Console.WriteLine(" " + g.Name);
}
}
}
string[] lines = System.IO.File.ReadAllLines(#"D:\C#\Tema1\Tema1.txt");
System.Console.WriteLine("Content Tema1.txt= \n");
foreach (string line in lines)
{
Console.WriteLine("\t" + line);
}
Console.WriteLine("\n Close");
System.Console.ReadKey();
}
You can also use the .NET TextFieldParser for that type of flat file:
var studentList = new List<Student>();
var parser = new Microsoft.VisualBasic.FileIO.TextFieldParser("<file path>");
parser.SetFieldWidths(4, 4, 12, 8, 2);
while (!parser.EndOfData)
{
string[] line = parser.ReadFields();
var student = new Student();
student.Year = int.Parse(line[0]);
student.Class = int.Parse(line[1]);
student.Name = line[2].Trim();
student.Surname = line[3].Trim();
student.Average = int.Parse(line[4]);
studentList.Add(student);
}
You just have to setup the field lengths in the SetFieldWidths function.
Your question is a vague one, are you looking for Linq like that:
// Parsing into objects
var data = System.IO.File
.ReadLines(#"D:\C#\Tema1\Tema1.txt")
.Skip(1) //TODO: comment down this line if your file doesn't have a caption
.Select(line => line.Split('\t'))
.Select(items => new { // or "new Student() {" if you've designed a Student class
Year = int.Parse(items[0]),
Class = int.Parse(items[1]),
Name = items[2],
Surname = items[3],
Average = int.Parse(items[4]), //TODO: Is it Int32 or Double?
});
...
// combining back:
String result = String.Join(Environment.NewLine, data
.Select(item => String.Join("\t",
item.Year, item.Class, item.Name, item.Surname, item.Average));
Console.Write(result);
If you want to have total control over what you want to do, I advise to create a class for each individual studet.
A rough approach:
namespace ConsoleApplication1
{
class Student
{
//Members of class
public int Year;
public int Class;
public string FirstName;
public string LastName;
public int Average;
/// <summary>
/// Gets a line and creates a student object
/// </summary>
/// <param name="line">The line to be parsed</param>
public Student(string line)
{
//being parsing
//split by space
List<String> unfiltered = new List<string>(line.Split(' '));
//a list to save filtered data
List<string> filtred = new List<string>();
//filter out empty spaces...
//There exist much smarter ways...but this does the job
foreach (string entry in unfiltered)
{
if (!String.IsNullOrWhiteSpace(entry))
filtred.Add(entry);
}
//Set variables
Year = Convert.ToInt32(filtred[0]);
Class = Convert.ToInt32(filtred[1]);
FirstName = filtred[2];
LastName = filtred[3];
Average = Convert.ToInt32(filtred[4]);
}
}
class Program
{
static void Main(string[] args)
{
var data = System.IO.File.ReadAllLines(#"d:\data.txt");
//a list to hold students
List<Student> students = new List<Student>();
foreach (var line in data)
{
//create a new student and add it to list
students.Add(new Student(line));
}
//to test, write all names
foreach (var student in students)
{
Console.WriteLine(student.FirstName + " " + student.LastName + Environment.NewLine);
}
//you can calculate average of all students averages!
int sum = 0;
for (int i = 0; i < students.Count; i++)
{
sum += students[i].Average;
}
//print average of all students
Console.WriteLine("Average mark of all students: " + (sum / students.Count));
Console.ReadKey();
}
}
}
Related
I have two objects they are: Student and Courses:
public Student(string StudentID, string Name, string Status, Enum StudentMajor, Dictionary<Courses, Grade[]> CompletedCourses)
public Courses(string courseName, string courseCode, string passingGrade, int numOfCredits, List<Courses> prerequisites)
Here's the objects I created in my Main class
//Courses
Courses ITEC_120 = new("Introduction to Computer Hardware", "ITEC 120", "C", 3, new List<Courses> {});
Courses ITEC_122 = new("Introduction to Operating Systems", "ITEC 122", "C", 3, new List<Courses> { ITEC_120 });
//Student
Student student1 = new("00069110", "Antony Dos Santos", "Full-time", Majors.Computer_Information_Systems, new Dictionary<Courses, Grade[]>()
{
{ ITEC_120, new[] { Grade.F, Grade.B, Grade.Not_Taken } },
{ ITEC_122, new[] { Grade.A, Grade.Not_Taken, Grade.Not_Taken }
},
});
As you can see the courses have a variable called credit and each Student object has a dictionary that takes a Course and a Grade
So student1 has two courses and each of the courses has 3 credits each. How would I iterate over the Dictionary to get the total of all the courses in CoursesCompleted in this case it should be 6.
Each object is added to a List
//List for Courses objects
List<Courses> CompulsoryCourses = new List<Courses>();
CompulsoryCourses.Add(ITEC_120);
CompulsoryCourses.Add(ITEC_122);//Adding the two courses to the List
List for Student objects
List<Student> students = new List<Student>();
students.Add(student1);
foreach(var stu in students)
{
var GPA = 0.0;
var CourseCredits = 0;
Console.WriteLine("\nStudent Information");
foreach (KeyValuePair<Courses, Grade[]> item in stu.CompletedCourses)
{
var TotalCredits = CourseCredits+item.Key.numOfCredits;
Console.WriteLine("\nName: " + item.Key.courseName + ", Credits: " + item.Key.numOfCredits);
GPA = stu.calGPA(CourseCredits);
Console.WriteLine("Total Credits: "+TotalCredits);
}
Console.WriteLine(stu.Name+ ": GPA = " + GPA);
}
In the foreach loop above I'm looping through the students List, and then I use another foreach loop to iterate the Dictionary to get the Key which in this case is numOfCredits like: item.Key.numOfCredits, and add them to each other.
Currently it's only adding the numOfCredits to itself and not to the other course in the dictionary.
You can use LINQ for something like this. If you have a list of cars and want to sum just the price you can do this:
var cars = new List<Car>
{
new Car{ BrandName = "Lamborghini", Model = "Huracan", Price = 300000M },
new Car{ BrandName = "Porsche", Model = "Gt3rs", Price = 200000M },
new Car{ BrandName = "Vauxhall", Model = "Corsa", Price = 20000M }
};
var totalPrice = cars.Sum(car => car.Price);
Console.WriteLine($"Total Price: {totalPrice}");
Where 'Car' looks like this:
public class Car
{
public string BrandName { get; set; }
public string Model { get; set; }
public decimal Price { get; set; }
}
Not sure exactly what you are asking for. But adding the sum of the cars "prices" i assume.
You could create a list, where all cars are added, along with all new cars.
Then what you could do it creating a for loop, thats the lengt of that spesific list. And through that loop add all values. Would look something like this:
Class creation
class Car
{
public string name;
public int price;
public Car(string name, int price)
{
this.name = name;
this.price = price;
}
}
Then for creating the list, and adding some cars.
Car car1 = new Car("blue-car", 15);
Car car2 = new Car("red-car", 15);
List<Car> cars = new List<Car>() { car1, car2 };
And then finnaly we count the sum up.
int totalprice = 0;
for (int i = 0; i < cars.Count; i++)
{
totalprice = totalprice + cars[i].price;
}
Output
If have only Student and Course classes (for simplification) and want this
Name: Andy
Credits: 4
GPA: 2.25
Course Credits Grade P/F
ITEC 100 1 C Fail
ITEC 100 1 B Pass
ITEC 122 3 C Pass
Name: Jill
Credits: 4
GPA: 3.75
Course Credits Grade P/F
ITEC 100 1 B Pass
ITEC 120 3 A Pass
Name: Peter
Credits: 4
GPA: 2.5
Course Credits Grade P/F
ITEC 100 1 A Pass
ITEC 122 3 C Pass
Name: Rosy
Credits: 4
GPA: 2.25
Course Credits Grade P/F
ITEC 100 1 B Pass
ITEC 122 3 F Fail
ITEC 122 3 D Fail
ITEC 122 3 C Pass
but with the additional logic of tracking passing and/or falling classes, and restrictions on re-enrolling into classes etc, then look at the example below:
Program
The test program below defines 3 classes and 5 students. Then enrolls students to classes and assigns grades. Finally it loops through each student and each class the student has taken to enumerate their grades, and also calculate GPA
static class Program
{
static void Main(string[] args)
{
var courses = new List<Course>
{
new Course("ITEC 100", "Introduction to Project Managment", 1, Grade.B),
new Course("ITEC 122", "Introduction to Operating Systems", 3, Grade.C),
new Course("ITEC 120", "Introduction to Computer Hardware", 3, Grade.D),
};
var students = new List<Student>
{
new Student("Andy"),
new Student("Jill"),
new Student("Peter"),
new Student("Rosy"),
};
students[0].EnrolledInClass(courses[0], Grade.C); // fail
students[0].EnrolledInClass(courses[0], Grade.B); // pass
students[0].EnrolledInClass(courses[1], Grade.C); // pass
students[1].EnrolledInClass(courses[0], Grade.B);
students[1].EnrolledInClass(courses[2], Grade.A);
students[2].EnrolledInClass(courses[0], Grade.A);
students[2].EnrolledInClass(courses[1], Grade.C);
students[3].EnrolledInClass(courses[0], Grade.B);
students[3].EnrolledInClass(courses[1], Grade.F); // fail
students[3].EnrolledInClass(courses[1], Grade.D); // fail
students[3].EnrolledInClass(courses[1], Grade.C); // fail
foreach (var student in students)
{
Console.WriteLine($"Name: {student.Name}");
Console.WriteLine($"Credits: {student.TotalCredits}");
Console.WriteLine($"GPA: {student.GPA}");
Console.WriteLine($" {"Course", -9} {"Credits",-8} {"Grade",-5} {"P/F",-5}");
foreach ((Course course, Grade grade) in student.Courses)
{
string pass = course.IsPassing(grade) ? "Pass" : "Fail";
Console.WriteLine($" {course.Code, -9} {course.Credits,-8} {grade,-5} {pass,-5}");
}
Console.WriteLine();
}
}
}
Logic
Most of the logic is in the Courses class where a particular grade is checked to see if it passes, it calculates the rewarded credit hours and the awarded credit-grades.
The data is stored in a private List<(Course,Grade)> per student, and methods exist to check if you can enroll and to enroll students as well as calculate credit hours and GPA.
public enum Grade
{
F = 0,
D,
C,
B,
A,
}
public class Student
{
private readonly List<(Course course, Grade grade)> _courses;
public Student(string name)
{
Name = name;
_courses = new List<(Course, Grade)>();
}
public string Name { get; }
public IReadOnlyList<(Course course, Grade grade)> Courses => _courses;
public int FirstIndexOf(Course course)
{
for (int i = 0; i < Courses.Count; i++)
{
var item = Courses[i];
if (item.course == course)
{
return i;
}
}
return -1;
}
public int LastIndexOf(Course course)
{
for (int i = Courses.Count - 1; i >= 0; i--)
{
var item = Courses[i];
if (item.course == course)
{
return i;
}
}
return -1;
}
public bool HasTakenCourse(Course course)
{
return FirstIndexOf(course) >= 0;
}
public bool HasPassedCourse(Course course)
{
int index = LastIndexOf(course);
if (index >= 0)
{
var item = Courses[index];
return course.IsPassing(item.grade);
}
return false;
}
public bool CanEnrollInCourse(Course course)
{
int takenCount = 0;
for (int i = 0; i < Courses.Count; i++)
{
var item = Courses[i];
if (item.course == course)
{
if (course.IsPassing(item.grade))
{
// Cannot enroll twice in same class with passing grade
return false;
}
takenCount++;
if (takenCount > 3)
{
// Cannot enroll in class > 3 times
return false;
}
}
}
return true;
}
public bool EnrolledInClass(Course course, Grade grade)
{
if (CanEnrollInCourse(course))
{
_courses.Add((course, grade));
return true;
}
return false;
}
public int TotalCredits
{
get
{
return Courses.Sum((item) => item.course.GetCredits(item.grade));
}
}
public float GPA
{
get
{
float creditGrades = Courses.Sum((item) => item.course.GetCreditGrade(item.grade));
return creditGrades / TotalCredits;
}
}
}
public class Course
{
public Course(string code, string description, int credits, Grade passingGrade = Grade.D)
{
Code = code;
Description = description;
Credits = credits;
PassingGrade = passingGrade;
}
public string Code { get; }
public string Description { get; }
public int Credits { get; }
public Grade PassingGrade { get; }
public bool IsPassing(Grade grade) => grade >= PassingGrade; // check if grade is passing
public int GetCredits(Grade grade) => IsPassing(grade) ? Credits : 0; // only credit passing grades
public float GetCreditGrade(Grade grade) => GetCredits(grade) * (int)grade; // combine credit hours with grades, or zero for fail
}
I have a mini assignment where I have to review the fundamentals of classes and properties. In the context of this code, I am trying to figure out how to print all the properties for each task that is stored in a list.
Here is the code. The commented out code is what I tried so far to print all the properties for each task stored in TaskList.
namespace FunProject
{
internal class Program
{
static void Main(string[] args)
{
var person1 = new Person
{
FirstName = "Mister",
LastName = "Programmer",
Age = 26
};
Console.WriteLine(person1.FullName());
var Task1 = new Task
{
TaskName = "read",
Description = "gain knowledge",
Id = 1,
IsDone = true
};
var Task2 = new Task
{
TaskName = "eat",
Description = "gain sustenance",
Id = 2,
IsDone = false
};
person1.TaskList = new List<Task>();
person1.TaskList.Add(Task1);
person1.TaskList.Add(Task2);
//Person1.TaskList.ForEach(i => Console.Write("{0}\t", i));
//Person1.TaskList.ForEach (x => Console.WriteLine(x));
//Console.WriteLine(String.Join("{0}\t", Person1.TaskList.ToString()));
//foreach (Task t in Person1.TaskList)
//{
// Console.WriteLine(t);
//}
Console.Read();
}
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set;}
public int Age { get; set; }
public List<Task>TaskList { get; set; }
public string FullName()
{
return ($"{FirstName} {LastName}");
}
}
public class Task
{
public int Id { get; set; }
public string TaskName { get; set;}
public string Description { get; set; }
public bool ?IsDone { get; set;}
}
}
Output should be something like:
Mister Programmer
Current Tasks:
TaskName: read
TaskDescription: gain knowledge
Id: 1
IsDone: true
TaskName: eat
TaskDescription: gain sustenance
Id: 2
IsDone: false
If you want to resolve this problem what I would do first, I will create task list something like this:
var list = new List<Task>();
list.Add(Task1);
list.Add(Task2);
And then I will add this list to the person that you are creating
var person1 = new Person
{
FirstName = "Mister",
LastName = "Programmer",
Age = 26,
TaskList = list
};
So now you have a person with the list of the tasks. Which is everything you need to create for the output.
So for the output you will need to format something like this:
Console.WriteLine(person1.FirstName + " " + person1.LastName);
Console.WriteLine("Current Tasks:");
person1.TaskList.ForEach(x => Console.WriteLine("TaskName:" + " " +
x.TaskName + "\n" + "TaskDescription:" + " " + x.Description + "\n" + "Id:" + " " + x.Id + "\n" + "IsDone:" + " " + x.IsDone.ToString().ToLower()));
Console.Read();
But if you want to have the properties names without writing the properties in the Console.WriteLine("TaskDescription") or etc. and also to get the values for each property from person object, you will need to use System.Reflection:
Type t = person1.GetType();
PropertyInfo[] properties = t.GetProperties();
foreach (PropertyInfo prop in properties)
{
if (!prop.Name.Equals("TaskList"))
{
Console.WriteLine($"{prop.Name}: {prop.GetValue(person1)}");
}
else
{
foreach (var t1 in person1.TaskList)
{
foreach (var propTask in t1.GetType().GetProperties())
{
Console.WriteLine($"{propTask.Name}: {propTask.GetValue(t1, null).ToString().ToLower()}");
}
Console.WriteLine("\n");
}
}
}
I would use System.Reflection for this...
foreach (var t in person1.TaskList)
{
foreach (var prop in t.GetType().GetProperties())
{
Console.WriteLine($"{prop.Name}: {prop.GetValue(t, null).ToString()}");
}
Console.WriteLine("\n");
}
OrderID=1211, OrderName=’Alice’, OrderDate= ‘15-10-2019’ //- row1
OrderID=1211, ItemID=1, ItemName=’Laptop’, ItemCompany=’Dell’, ItemPrice=’40000’ //row2
OrderID=1211, ItemID=2, ItemName=’Mouse’, ItemCompany=’Logitech’, ItemPrice=’5000’ //3
OrderID=4322, OrderName=’Ben’, OrderDate= ‘1-10-2019’//4
OrderID=4322, ItemID=1, ItemName=’Laptop’, ItemCompany=’Microsoft’, ItemPrice=’40000’//5
OrderID=4322, ItemID=2, ItemName= ‘Keyboard’, ItemCompany=’Microsoft’, ItemPrice=’12000’ //6
static void Main(string[] args)
{
Dictionary<dynamic, dynamic> yourDic = new Dictionary<dynamic, dynamic>();
StreamReader sr = new StreamReader(#"c:Probb.txt");
bool first = true;
while (sr.Peek() >= 0)
{
string line = sr.ReadLine();
string[] data = line.Split(',');
if (first == false)
{
if (!yourDic.ContainsKey(line.Split(',')[0]))
{
yourDic.Add(line.Split(',')[0], line.Split(',')[1] + "," + line.Split(',')[2]);
}
else if (!yourDic.ContainsKey(line.Split(',')[1]))
{
yourDic.Add(line.Split(',')[1], line.Split(',')[2] + "," + line.Split(',')[3] + "," + line.Split(',')[4]);
}
else
{
yourDic.Add(line.Skip(1), line.Split(',')[2] + "," + line.Split(',')[3] + "," + line.Split(',')[4]);
}
Console.WriteLine(line);
}
first = false;
}
foreach (KeyValuePair<dynamic, dynamic> kvp in yourDic)
{
Console.WriteLine(" {0},\n {1}", kvp.Key, kvp.Value);
}
}
}
}
Thanks for trying. I am new to C# and don't know how to access the specific data. output: OrderId:1211 Order Name=Alice, Total Id=2, Total Price=45000
Because the Dictionary must have a unique key, you need to save all order items in the same key. If I got you question correctly you want to get sum of item price for each OrderId.
By this way I think this should work:
public class Order
{
public string OrderName { get; set; }
public string OrderDate { get; set; }
public List<OrderItem> OrderItems { get; set; }
}
public class OrderItem
{
public int ItemId { get; set; }
public int ItemPrice { get; set; }
}
var dictItems = new Dictionary<string, Order>();
var allLines = File.ReadAllLines("test.txt").ToList();
foreach (var line in allLines)
{
var splitLine = line.Split(',');
if (dictItems.ContainsKey(splitLine[0]))
dictItems[splitLine[0]].OrderItems.Add(new OrderItem()
{
ItemId = int.Parse(splitLine[1].Split('=')[1]),
ItemPrice = int.Parse(splitLine[4].Split('=')[1].Replace("’", ""))
});
else
dictItems.Add(splitLine[0],
new()
{
OrderName = splitLine[1].Split('=')[1].Replace("’", ""),
OrderDate = splitLine[2].Split('=')[1].Replace("’", ""),
OrderItems = new List<OrderItem>()
});
}
foreach (var dictItem in dictItems)
{
Console.WriteLine(" {0},\n OrderName: {1} \n Total: {2} \n TotalPrice: {3}", dictItem.Key, dictItem.Value.OrderName, dictItem.Value.OrderItems.Count, dictItem.Value.OrderItems.Sum(x => x.ItemPrice));
}
Of course, you need to check the real data for preventing exception in convert string to int.
I'm trying to sort through a 2d list in C#. I have code written that lets me create a list from data pulled from a CSV file, however I'm stuck on the function to sort them.
The list details the shop ID, item, and price, and is formatted thusly:
1,shirt,5
1,pants,3
2,hat,3
I'm trying to find a way to take a user input, say 'shirt' and return the ID of the shop, and the price. How do I do this?
Here is the full code.
namespace Shop
{
public class ShopPick
{
private class Shop
{
public int ShopId { get; set; }
public Dictionary<string, decimal> Goods { get; set; }
}
private readonly List<Shop> _Shops = new List<Shop>();
public void ReadShopData(string filePath)
{
try
{
var records = File.ReadLines(filePath);
foreach (var record in records)
{
var data = record.Split(',');
var ShopId = int.Parse(data[0].Trim());
var Shop = _Shops.Find(r => r.ShopId == ShopId);
if (Shop == null)
{
Shop = new Shop { Goods = new Dictionary<string, decimal>() };
_Shops.Add(Shop);
}
Shop.ShopId = ShopId;
Shop.Goods.Add(data.Skip(2).Select(s => s.Trim()).Aggregate((a, b) => a.Trim() + "," + b.Trim()), decimal.Parse(data[1].Trim()));
}
}
catch (FileNotFoundException ex)
{
Console.WriteLine(ex.Message);
}
}
static void Main(string[] args)
{
var ShopPicker = new ShopPick();
ShopPicker.ReadShopData(
Path.GetFullPath(
Path.Combine(
AppDomain.CurrentDomain.BaseDirectory, #"../../../../Shop_data.csv")
)
);
// Item is found in Shop 2 at price 6.50
var bestShop = ShopPicker.PickBestShop("gac");
Console.WriteLine(bestShop.Item1 + ", " + bestShop.Item2);
Console.WriteLine("Done!");
Console.ReadLine();
}
public Tuple<int, decimal> PickBestShop(string items)
{
string input = Console.ReadLine();
string[] choices = input.Split(',');
foreach(var Shop in _Shops)
{
}
return new Tuple<int, decimal>(0, 0);
}
}
}
The function PickBestShop is where I am stuck
You can use Linq statements. The following code will give you an IEnumerable with the single product Id. Of course you'll need to check for empty lists and nulls and things like that. The code is assuming a product has at least the fields Id and Name.
products.Where(product => product.Name == name).Select(product => product.Id)
I made some edits based on what I could understand from your question. The content in c:\temp\shop.csv looks like:
1,shirt,5
1,pants,3
2,hat,3
3,shirt,6
3,hat,2
4,pants,2
3,trousers,20
5,shirt,5
5,hat,2
And this is edited code:
static void Main(string[] args)
{
//string fileName = Path.GetFullPath(Path.Combine(
// AppDomain.CurrentDomain.BaseDirectory, #"../../../../Shop_data.csv")
// );
string fileName = #"c:\temp\shops.csv";
var ShopPicker = new ShopPick(fileName);
var sample = ShopPicker.PickBestShop("shirt, Hat");
foreach (var shop in sample)
{
Console.WriteLine($"ShopId:{shop.ShopId}, Product: {shop.Product}, Price: {shop.Price}");
}
}
public class ShopPick
{
private List<Shop> _Shops;
public class Shop
{
public int ShopId { get; set; }
public string Product { get; set; }
public decimal? Price { get; set; }
}
public ShopPick(string filePath)
{
var records = File.ReadLines(filePath)
.Select(line => line.Split(','))
.Select(line => new Shop
{
ShopId = int.TryParse(line[0], out int sId) ? sId : -1,
Product = line[1].Trim(),
Price = decimal.TryParse(line[2], out decimal p) ? p : (decimal?)null
});
this._Shops = records.ToList();
}
//public List<Shop> Shops { get { return this._Shops; } }
public IEnumerable<Shop> PickBestShop(string items)
{
List<Shop> shops = new List<Shop>();
//string input = Console.ReadLine();
var choices = items.Split(',').Select(p => p.Trim().ToLower());
foreach (var item in choices)
{
var _shops = this._Shops.Where(s => s.Product.ToLower() == item);
if (_shops.Any())
{
var minPrice = _shops.Min(s => s.Price);
shops.AddRange(_shops.Where(s => s.Price == minPrice));
}
}
return shops;
}
}
Outputs:
ShopId:1, Product: shirt, Price: 5
ShopId:5, Product: shirt, Price: 5
ShopId:3, Product: hat, Price: 2
ShopId:5, Product: hat, Price: 2
Please inform if that wasn't what you meant and\or you require explanation on any part.
The Text File Data is Like Below:
S.No Name Description Quantity Rate Discount Amount
1 Apple Friut is 12 24.02 0 242
Good for
health
2 Orange Friut 5 12.22 3 128
3 Banana Friut 5 12.22 3 128
4 Grapes Friut 5 12.22 3 128
I want to add all the Rows& Columns in list but Description column have multiple Rows in single item. How can I Solve this. I add My Existing Code Here:
My Existing Code is as follows:
class Program
{
static void Main(string[] args)
{
var dd = File.ReadAllLines(
"C:\\Users\\Trainee\\Desktop\\Saravanan_Test\\27.8.2018\\Inputfile.txt")
.Skip(1)
.Where(s => s.Length > 1)
.Select(x => splits(x)).ToList();
foreach (var item in dd)
{
Console.WriteLine(item.id+"\t"
+ item.Name+"\t"
+ item.Description+"\t"
+ item.Quantity+"\t"
+ item.Rate+"\t"
+ item.Discount+"\t"
+ item.Amount);
}
Console.ReadKey();
}
private static Class1 splits(string x)
{
var columns = x.Split('\t').Where(c => c != "").ToList();
return new Class1
{
id = Convert.ToInt32(columns[0]),
Name = columns[1],
Description = columns[2],
Quantity = Convert.ToInt32(columns[3]),
Rate = Convert.ToDouble(columns[4]),
Discount = Convert.ToInt32(columns[5]),
Amount = int.Parse(columns[6])
};
}
}
class Class1
{
public int id { get; set; }
public string Name { get; set; }
public String Description { get; set; }
public int Quantity { get; set; }
public double Rate { get; set; }
public int Discount { get; set; }
public int Amount { get; set; }
}
I want to store data into list like:
list.Add(new{ sno=1, Name="Apple",
Description="Friut is good for Health",
Quantity=12, Rate=24.02, Discount=0,
Amount=242 });
Thanks in Advance.
NOTE: This solution is based on the file shared in question. Data is separated by spaces and format is not advisable to use. Answering to help person with content format he has. Tested and working.
static void Main(string[] args)
{
List<Data> list = new List<Data>();
var dd = File.ReadAllLines(#"C:\Users\XXXX\Desktop\test.txt")
.Skip(1)
.Where(s => s.Length > 1).ToList();
foreach (var item in dd)
{
var columns = item.Split('\t').Where(c => c.Trim() != string.Empty).ToList();
if (columns != null && columns.Count > 0)
{
int id;
if (int.TryParse(columns[0], out id))
{
list.Add(new Data()
{
id = Convert.ToInt32(columns[0]),
Name = columns[1],
Description = columns[2],
Quantity = Convert.ToInt32(columns[3]),
Rate = Convert.ToDouble(columns[4]),
Discount = Convert.ToInt32(columns[5]),
Amount = int.Parse(columns[6])
});
}
else
{
list.Last().Description += columns[0];
}
}
}
Console.ReadLine();
}