I have a large list of hardware parts, where each part has a name and sales count.
Sample collection below:
var parts = new List<(string name, int sales)>{
("Part A", 400),
("Part B", 600),
("Part A", 600),
("Part C", 400),
("Part D", 1500),
("Part B", 500),
("Part A", 475),
("Part B", 400),
("Part E", 700),
("Part A", 700),
};
This list of parts is sorted, first by the sales count:
var results = parts.OrderByDescending(p => p.sales).ToList();
/*
Results:
Part D - 1500
Part E - 700
Part A - 700
Part B - 600
Part A - 600
Part B - 500
Part A - 475
Part A - 400
Part C - 400
Part B - 400
*/
Now, the second ordering I need is for same part names to be together as long as their sales are within a range of 100 of each other, but keeping the first ordering intact.
/*
Final results:
Part D - 1500
Part E - 700
Part A - 700
Part A - 600
Part B - 600
Part B - 500
Part B - 400
Part A - 475
Part A - 400
Part C - 400
*/
How can this be achieved in an efficient way, so that it also performs well on large datasets?
does this solve it?
var results = parts
.OrderByDescending(p => Math.Floor(p.sales/100))
.ThenBy(p => p.name)
.ToList();
It depends on what "large datasets" means.
var parts = new List<(string Name, int Sales)?>{
("Part A", 400),
("Part B", 600),
("Part A", 600),
("Part C", 400),
("Part D", 1500),
("Part B", 500),
("Part A", 475),
("Part B", 400),
("Part E", 700),
("Part A", 700),
};
parts = parts.OrderByDescending(p => p.Value.Sales).ToList();
List<(string Name, int Sales)> sortedParts = new();
for (int i = 0; i < parts.Count; i++)
{
if (parts[i] is not null)
{
sortedParts.Add(parts[i].Value);
for (int j = i+1; j < parts.Count; j++)
{
if (parts[j] is not null && parts[i].Value.Name == parts[j].Value.Name
&& parts[j].Value.Sales >= sortedParts.Last().Sales - 100
&& parts[j].Value.Sales <= sortedParts.Last().Sales + 100)
{
sortedParts.Add(parts[j].Value);
parts[j] = null;
}
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.