Reputation:
I have one outer List BigList and then in my switch statements I have a bunch of other List smallerList variables. When I get to each of these cases in my switch I want to add those to the BigList But I also don't want to add repeated ones. How do we do that?
private List<string> MyMethod()
{
List<string> BigList = null;
for each( string name in MyListOfStringsThatComesIn)
{
tName = name;
switch(tName)
{
case "dsdds":
// List<string> smallerList;
// add it to BigList
case "fdfdf":
// List<string> smallerList2;
// add it to BigList
case "vbbughb":
// List<string> smallerList3;
// add it to BigList
Upvotes: 2
Views: 1719
Reputation: 460038
If duplicates aren't allowed i would use a HashSet<string>
in the first place:
HashSet<string> bigSet = new HashSet<string>();
// add strings ...
If you want to add the whole List<string>
into the set you can either use bigSet.Add
in a loop or HashSet.UnionWith
:
case "dsdds":
bigSet.UnionWith(smallerList);
If you need to return a list you can use
return new List<string>(bigSet);
Upvotes: 4
Reputation: 152501
Well, there's probably a more efficient way to do what you want, but based on what you have shown, you can either:
Look for strings that don;t exist in the parent list:
BigList.AddRange(smallerList.Except(BigList));
or just add them all (allowing duplicates) and call Distinct
at the end:
BigList.AddRange(smallerList);
...
///add other lists
BigList = BigList.Distinct().ToList();
Also, you should probably intialize your list to an empty list rather then null
:
List<string> BigList = new List<string>();
Upvotes: 1
Reputation: 14477
To create a new list based on the unique values of another one :
List<string> BigList = MyListOfStringsThatComesIn.Distinct().ToList();
To add new unique values from another list :
//assume the BigList contains something already...
BigList.AddRange(BigList.Except(MyListOfStringsThatComesIn));
Upvotes: 1