Split ObservableCollection into limited amount collection [duplicate] - c#

This question already has an answer here:
how to split ObservableCollection
(1 answer)
Closed 2 years ago.
I'm working on a payment report printer for work and have an ObservableCollection that fills when the client's name is selected. So, for example, I have a collection name Clients which can have up to only 60 entries. For printing purposes, I need to separate this into 5 separate lists and I can't think of how to go about it.
This is the class for the items used if helps any
public class payment
{
public string amount { get; set; }
public string date { get; set; }
}

I have a collection name Clients which can have up to only 60 entries. For printing purposes, I need to separate this into 5 separate lists
I guess this might look something like:
// An observable collection of 60 items
var clients = new ObservableCollection<Payment>(
Enumerable.Range(0, 60).Select(i => new Payment {Amount = i.ToString()}));
// The number of lists to create
var numLists = 5;
var itemsPerList = clients.Count / numLists + 1;
// Create a list of new ObservableCollections
var smallerCollections = new List<ObservableCollection<Payment>>();
// Copy the items from 'clients' into smaller collections of
// 'itemsPerList' size, and add those to the smallerCollections list
for (var i = 0; i < clients.Count; i++)
{
// Add a new list every time we add 'itemsPerList' items
if (i % itemsPerList == 0) smallerCollections.Add(new ObservableCollection<Payment>());
// Add this item to the last list
smallerCollections.Last().Add(clients[i]);
}

Related

display list items into data grid view c#

I have a super-class (abstract) and then 2 inherited classes.
SuperClass: Sessions
Class 1: Cycling
Class 2: Running
I also have a list that will hold all of my objects private List<Session> allSessions = new List<Session>();
I also have declared some arrays that hold hard-coded data to populate my objects.
Also, Running and Cycling has an overridden ToString() method that displays different data depending on the class.
public override string ToString() => $"Cycle Average RPM is {AverageRpm} and Average Resistance is {AverageResistance}";
I am using a for loop to create and add new objects into my list like this
for (int i = 0; i < id.Length; i++)
{
Cycling Cycle = new Cycling(id[i], titles[i], date[i], duration[i], difficulty[i], instructor[i],
description[i], averageRpm[i], averageResistance[i]);
// Add new objects to list
allSessions.Add(Cycle);
}
I have a dataGridView that is getting everything from my list and displays it like this:
My problem now is, that I want to display only specific data depending on what you choose in the ComboBox, but something is not working,
The overridden ToString() is not added to the list for some reason and whenever I choose a different option from the ComboBox, nothing is being displayed.
EDIT 1:
// Filter Sessions by type using Linq
var sessions = new List<Session>();
var cyclingSessions = sessions.OfType<Cycling>();
var runningSessions = sessions.OfType<Running>();
listBox1.DataSource = null;
listBox1.Items.Clear();
if (cboMenu.SelectedIndex == 0)
{
// Populate GridView with data
dataDisplay.DataSource = allSessions;
}
else if (cboMenu.SelectedIndex == 1)
{
// Populate GridView with data
dataDisplay.DataSource = cyclingSessions;
}
else
{
// Populate GridView with data
dataDisplay.DataSource = runningSessions;
}
}
You need to filter your sessions list and set that as your data source you can easily filter the list using OfType from System.Linq It would look something like this:
var sessions = new List<Sessions>();
var cyclingSessions = sessions.OfType<Cycling>();
var runningSessions = sessions.OfType<Running>();
dataDisplay.DataSource = cyclingSessions;

How do I store the initial state of a list of objects so that I can compare them to an updated list?

I have a list that is constantly being updated throughout my program. I would like to be able to compare the initial count and final count of my list after every update. The following is just a sample code (the original code is too lengthy) but it sufficiently captures the problem.
class Bot
{
public int ID { get; set; }
}
public class Program
{
public void Main()
{
List<Bot> InitialList = new List<Bot>();
List<Bot> FinalList = new List<Bot>();
for (int i = 0; i < 12345; i++)
{
Bot b = new Bot() {ID = i};
InitialList.Add(b);
}
FinalList = InitialList;
for (int i = 0; i < 12345; i++)
{
Bot b = new Bot() {ID = i};
FinalList.Add(b);
}
Console.Write($"Initial list has {InitialList.Count} bots");
Console.Write($"Final list has {FinalList.Count} bots");
}
}
Output:
Initial list has 24690 bots
Final list has 24690 bots
Expected for both lists to have 12345 bots.
What is correct way to copy the initial list so new set is not simply added to original?
To do what you seem to want to do, you want to copy the list rather than assign a new reference to the same list. So instead of
FinalList = InitialList;
Use
FinalList.AddRange(InitialList);
Basically what you had was two variables both referring to the same list. This way you have two different lists, one with the initial values and one with new values.
That said, you could also just store the count if that's all you want to do.
int initialCount = InitialList.Count;
FinalList = InitialList;
Although there's now no longer a reason to copy from one to the other if you already have the data you need.
I get the feeling you actually want to do more than what's stated in the question though, so the correct approach may change depending on what you actually want to do.

Sorting List Array based on an index of array

I want to sort a List Array on the basis of an array item.
I have a List Array of Strings as below:
List<String>[] MyProjects = new List<String>[20];
Through a loop, I have added five strings
(Id, Name, StartDate, EndDate, Status)
to each of the 20 projects from another detailed List source.
for(int i = 0; i<20; i++){
MyProjects[i].Add(DetailedProjectList.Id.ToString());
MyProjects[i].Add(DetailedProjectList.Name);
MyProjects[i].Add(DetailedProjectList.StartDate);
MyProjects[i].Add(DetailedProjectList.EndDate);
MyProjects[i].Add(DetailedProjectList.Status)}
The Status values are
"Slow", "Normal", "Fast", "Suspended" and "" for unknown status.
Based on Status, I want to sort MyProject List Array.
What I have done is that I have created another List as below
List<string> sortProjectsBy = new List<string>(){"Slow", "Normal", "Fast", "", "Suspended"};
I tried as below to sort, however unsuccessful.
MyProjects = MyProjects.OrderBy(x => sortProjectsBy.IndexOf(4));
Can anyone hint in the right direction. Thanks.
I suggest you to create class Project and then add all the fields inside it you need. It's much nicer and scalable in the future. Then create a List or an Array of projects and use the OrderBy() function to sort based on the field you want.
List<Project> projects = new List<>();
// Fill the list...
projects.OrderBy(project => project.Status);
The field Status has to be a primitive type or needs to implement the interface IComparable in order for the sorting to work. I suggest you add an enum for Status with int values.
First consider maybe to use Enum for status and put it in a different file lite (utils or something) - better to work like that.
enum Status {"Slow"=1, "Normal", "Fast", "", "Suspend"}
Now about the filtering you want to achieve do it like this (you need to tell which attribute of x you are referring to. In this case is status)
MyProjects = MyProjects.OrderBy(x => x.status == enum.Suspend);
Read about enums :
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/enum
Read about lambda expressions :
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/lambda-expressions
First of all, storing project details as List is not adivisable. You need to create a Custom Class to represent them.
For example,
public class DetailedProjectList
{
public string Name {get;set;}
public eStatus Status {get;set;}
// rest of properties
}
Then You can use
var result = MyProjects.OrderBy(x=> sortProjectsBy.IndexOf(x.Status));
For example
List<string> sortProjectsBy = new List<string>(){"Slow", "Normal", "Fast", "", "Suspended"};
var MyProjects= new List<DetailedProjectList>{
new DetailedProjectList{Name="abc1", Status="Fast"},
new DetailedProjectList{Name="abc2", Status="Normal"},
new DetailedProjectList{Name="abc3", Status="Slow"},
};
var result = MyProjects.OrderBy(x=> sortProjectsBy.IndexOf(x.Status));
Output
abc3 Slow
abc2 Normal
abc1 Fast
A better approach thought would be to use Enum to represent Status.
public enum eStatus
{
Slow,
Normal,
Fast,
Unknown,
Suspended
}
Then your code can be simplified as
var MyProjects= new List<DetailedProjectList>{
new DetailedProjectList{Name="abc1", Status=eStatus.Fast},
new DetailedProjectList{Name="abc2", Status=eStatus.Normal},
new DetailedProjectList{Name="abc3", Status=eStatus.Slow},
};
var result = MyProjects.OrderBy(x=> x.Status);
Ok so you have a collection of 20 items. Based on them you need to create a list of strings(20 DetailedProjectList items).
What you can do to solve your problem is to SORT YOUR COLLECTION before you create your list of strings. In this way your list of strings will be sorted.
But your code is not optimal at all. So you should concider optimization on many levels.
Lets say you have ProjectDetail class as follow:
private class ProjectDetail
{
public int Id {get;set;}
public string Name {get;set;}
DateTime StartDate {get;set;} = DateTime.Now;
DateTime EndDate {get;set;} = DateTime.Now;
public string Status {get;set;}
public string toString => $"{Id} - {Name} - {StartDate} - {EndDate} - {Status}";
}
Notice that I have added a toString attribute to make things easier, and I also have added default values.
Then your program could be like:
static void Main(string[] args)
{
var projectDetails = MockProjectItems();
Console.WriteLine("Before sortig:");
foreach (var item in projectDetails)
{
Console.WriteLine(item.toString);
}
var myProjects = projectDetails.OrderBy(p => p.Status).Select(p => p.toString);
Console.WriteLine("\n\nAfter sorting:");
foreach (var item in myProjects)
{
Console.WriteLine(item);
}
}
where the helper method is
private static List<ProjectDetail> MockProjectItems()
{
var items = new List<ProjectDetail>(20);
for(int i = 0; i < 20 ; i += 4){
items.Add(new ProjectDetail{Id = i, Name = "RandomName "+i, Status = "Slow"});
items.Add(new ProjectDetail{Id = i+1, Name = "RandomName "+(i+1), Status = "Normal"});
items.Add(new ProjectDetail{Id = i+2, Name = "RandomName "+(i+2), Status = "Fast"});
items.Add(new ProjectDetail{Id = i+3, Name = "RandomName "+(i+3), Status = "Suspended"});
}
return items;
}
Then your program should print the following:

Removing duplicate objects from a list [duplicate]

This question already has answers here:
Remove duplicates from a List<T> in C#
(32 answers)
Closed 7 years ago.
I am currently working on a project and have hit a snag.
I'm taking in an unformatted string[] of football teams and I'm trying to filter the data and return it in a more orgainised format.
I'm fine with most of it (splitting the string to get the relevant values and sorting the format) except i have created a Team object which holds most of this data and as i loop through the original string i create a new team object each time i see a team name. Then i check to see if i've seen that object before and if i have i don't create a new object. After creating the Team or skipping that part i add the relevant info to the team object and continue.
My issue is the list i'm using to hold the final team info has many duplicates mean my check to see if the object exists or not doesn't work. The code is :
After splitting string,
List<Team> teams = new List<Team>();
for (int i = 1; i <= matches.Length - 1; i++)
{
string fullStr = matches[i];
string[] score = fullStr.Split(',');
string[] team1 = score[0].Split('!');
string team1Name = team1[0];
Team teams1 = new Team(team1Name);
if (teams.Contains(teams1) != true)
{
teams.Add(teams1);
}
string team1Score = team1[1];
int team1ScoreInt = int.Parse(team1Score);
string[] team2 = scores[1].Split('!');
string team2Name = team2[1];
Team teams2 = new Team(team2Name);
if (!teams.Contains(teams2))
{
teams.Add(teams2);
}
When i print the list i get the format i want but multiple Germanys etc. And only the score etc of that 1 game rather than them all adding to 1 Germany Team object.
Any ideas how i can stop the duplicates and maintain using only the 1 Team object every time i see that team name?
Thanks
You can implement IEqualityComparer for Team class and check equality of objects based on its values. Something like below.
using System.Collections.Generic;
public class Team{
public string Name {get;set;}
public int score {get;set;}
}
//Create some dummy data
public List<Team> lstTeam = new List<Team>{
new Team{Name="A", score=1},
new Team{Name="A", score=1},
new Team{Name="B", score=1},
new Team{Name="C", score=2},
new Team{Name="A", score=2},
new Team{Name="C", score=2}
};
List<Team> lstDistictTeams = lstTeam.Distinct<Team>(new DistinctComparer()).ToList();
foreach(Team t in lstDistictTeams)
{
Console.WriteLine("Team {0} has Score {1}",t.Name,t.score);
}
//This class provides a way to compare two objects are equal or not
public class DistinctComparer : IEqualityComparer<Team>
{
public bool Equals(Team x, Team y)
{
return (x.Name == y.Name && x.score == y.score); // Here you compare properties for equality
}
public int GetHashCode(Team obj)
{
return (obj.Name.GetHashCode() + obj.score.GetHashCode());
}
}
Here is running example : http://csharppad.com/gist/6428fc8738629a36163d
Looks like the problem is you're creating a new Team object with the name of the team for each result.
When you then compare against the list to see if it is contained, you're checking to see if there's a reference to that object in the list, and as you've just created it, there won't be, so every Team object you create will be added to the list.
You'll need to check whether the list contains a Team object with the name, rather than just check for the instance of the object.

Creating and Displaying multiple arrays simultaniously C#

I'm new to C# and programming as a whole and I've been unable to come up with a solution to what I want to do. I want to be able to create a way to display several arrays containing elements from three external text files with values on each line (e.g. #"Files\Column1.txt", #"Files\Column2.txt" #"Files\Column3.txt"). They then need to be displayed like this in the command line:
https://www.dropbox.com/s/0telh1ils201wpy/Untitled.png?dl=0
I also need to be able to sort each column individually (e.g. column 3 from lowest to highest).
I've probably explained this horribly but I'm not sure how else to put it! Any possible solutions will be greatly appreciated!
One way to do it would be to store the corresponding items from each file in a Tuple, and then store those in a List. This way the items will all stay together, but you can sort your list on any of the Tuple fields. If you were doing anything more detailed with these items, I would suggest creating a simple class to store them, so the code would be more maintainable.
Something like:
public class Item
{
public DayOfWeek Day { get; set; }
public DateTime Date { get; set; }
public string Value { get; set; }
}
The example below could easily be converted to use such a class, but for now it uses a Tuple<string, string, string>. As an intermediate step, you could easily convert the items as you create the Tuple to get more strongly-typed versions, for example, you could have Tuple<DayOfWeek, DateTime, string>.
Here's the sample code for reading your file items into a list, and how to sort on each item type:
public static void Main()
{
// For testing sake, I created some dummy files
var file1 = #"D:\Public\Temp\File1.txt";
var file2 = #"D:\Public\Temp\File2.txt";
var file3 = #"D:\Public\Temp\File3.txt";
// Validation that files exist and have same number
// of items is intentionally left out for the example
// Read the contents of each file into a separate variable
var days = File.ReadAllLines(file1);
var dates = File.ReadAllLines(file2);
var values = File.ReadAllLines(file3);
var itemCount = days.Length;
// The list of items read from each file
var fileItems = new List<Tuple<string, string, string>>();
// Add a new item for each line in each file
for (int i = 0; i < itemCount; i++)
{
fileItems.Add(new Tuple<string, string, string>(
days[i], dates[i], values[i]));
}
// Display the items in console window
fileItems.ForEach(item =>
Console.WriteLine("{0} {1} = {2}",
item.Item1, item.Item2, item.Item3));
// Example for how to order the items:
// By days
fileItems = fileItems.OrderBy(item => item.Item1).ToList();
// By dates
fileItems = fileItems.OrderBy(item => item.Item2).ToList();
// By values
fileItems = fileItems.OrderBy(item => item.Item3).ToList();
// Order by descending
fileItems = fileItems.OrderByDescending(item => item.Item1).ToList();
// Show the values based on the last ordering
fileItems.ForEach(item =>
Console.WriteLine("{0} {1} = {2}",
item.Item1, item.Item2, item.Item3));
}

Categories

Resources