0

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?

4
  • 2
    Please check stackoverflow.com/questions/2779375/… for an answer. Commented Jun 8, 2021 at 7:59
  • 1
    What is your inefficient try ? Commented Jun 8, 2021 at 7:59
  • Didn't you ask almost the same question a few days ago? stackoverflow.com/questions/67869527/… Commented Jun 8, 2021 at 8:25
  • @Klamsi That other question is similar, but not the same or close to what this question is about. Thanks. Commented Jun 8, 2021 at 8:27

2 Answers 2

1

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; } } } } 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Klamsi. Clever use of nullable value type tuples. Works well for most scenarios. I'll test it a bit more.
1

does this solve it?

var results = parts .OrderByDescending(p => Math.Floor(p.sales/100)) .ThenBy(p => p.name) .ToList(); 

1 Comment

Thanks Matthias. Unfortunately, it doesn't group same part names within range, together.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.