Condense a list
-
I have a list of a custom type that contains 2 variables. One is name, the other is count. What is the general idea of what I need to do in order to condense this into a list with no duplicates where the counts of duplicate names are added together? (eg. A list with 3 carls, 2 carls, 1 eric, 1 alex and 1 eric should condense to 5 carls, 2 ercis, 1 alex) An example of the class the list would be populated with:
public class Person
{
private string _name;public string PersonName { get {return \_name;} set { \_name = value;} } private int \_count; public int PersonCount { get { return \_count; } set { \_count = value; } } public Person(string name, int count) { \_count = count; \_name = name; } }
-
I have a list of a custom type that contains 2 variables. One is name, the other is count. What is the general idea of what I need to do in order to condense this into a list with no duplicates where the counts of duplicate names are added together? (eg. A list with 3 carls, 2 carls, 1 eric, 1 alex and 1 eric should condense to 5 carls, 2 ercis, 1 alex) An example of the class the list would be populated with:
public class Person
{
private string _name;public string PersonName { get {return \_name;} set { \_name = value;} } private int \_count; public int PersonCount { get { return \_count; } set { \_count = value; } } public Person(string name, int count) { \_count = count; \_name = name; } }
and is that a problem? There are many ways to do it: 1. avoid duplicates from the start; that is the cheapest solution. See also (4) 2. use two nested for loops, and merge entries with identical names (one gets the sum, the other gets removed) 3. for better performance, you could sort the list on the name (this[^] may help), then do as in (2) 4. create a new list which never holds any duplicates; the easiest way to do that is by using a Dictionary where name would be the key, and count the value. You'll have to choose one and work out the details yourself. :)
Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]
I only read code that is properly indented, and rendered in a non-proportional font; hint: use PRE tags in forum messages
-
and is that a problem? There are many ways to do it: 1. avoid duplicates from the start; that is the cheapest solution. See also (4) 2. use two nested for loops, and merge entries with identical names (one gets the sum, the other gets removed) 3. for better performance, you could sort the list on the name (this[^] may help), then do as in (2) 4. create a new list which never holds any duplicates; the easiest way to do that is by using a Dictionary where name would be the key, and count the value. You'll have to choose one and work out the details yourself. :)
Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]
I only read code that is properly indented, and rendered in a non-proportional font; hint: use PRE tags in forum messages