I have a list of user IP addresses like following:
user 1:
192.168.1.1
192.168.1.2
192.168.1.3
user 2:
192.168.1.1
192.168.1.2
192.168.1.3
172.0.0.1
172.0.0.5
174.5.5.15
Now what I'd like to do here is to filter out all the IP's that are obviously from the same subnet/coming from the same PC/City.
I'm only using local IP's as an example here.
After filtering I would be left with the following:
For user 1 it is enough for me to have only 1 IP from each subnet like following:
192.168.1.1 => all other IP's would be removed, only one would be left
from that specific subnet
For user 2:
192.168.1.1
172.0.0.1
174.5.5.15
For the user 2 I'm left with 3 IP's since 192.168.. and 172.0.. had multiple ip's from that range.
Now my idea is to use a criteria for the first two numbers of the IP to be compared. For example:
192.168.0.1
192.168.0.2
192.168.0.6
These 3 have same first two numbers (192.168), thus I can consider them as duplicates and they should be removed. Which ever 1 of the IP's is left here from these is irrelevant, what matters is is that only 1 is left.
This would result in 1 ip to be left, for example:
192.168.0.1 (again doesn't matter which one is left, just that 1 is left!)
Now onto the part with code. I have a class structure like following:
public class SortedUser
{
public string Email { get; set; }
public List<IpInfo> IPAndCountries = new List<IpInfo>();
}
And IPInfo class looks like this:
public class IpInfo
{
public string Ip { get; set; }
}
Can someone help me out with this now? How can I do it in most easiest way?
If you are looking for only the first two bytes in the list of addresses, you can run a string comparison like so (not tested):
SortedUser user = new SortedUser()
{
Email = "Foo#bar.com",
IPAndCountries = new List<IpInfo>()
{
new IpInfo() {Ip = "192.168.0.1"},
new IpInfo() {Ip = "192.168.1.2"},
new IpInfo() {Ip = "193.168.3.2"},
new IpInfo() {Ip = "8.2.4.5"}
}
};
// Using ToArray to avoid collection modified errors
foreach (IpInfo item in user.IPAndCountries.ToArray())
{
string[] ipSplit = item.Ip.Split('.');
string prefix = $"{ipSplit[0]}.{ipSplit[1]}";
user.IPAndCountries.RemoveAll(info => info.Ip.StartsWith(prefix) && info.Ip != item.Ip);
}
Related
I have two variables, State and Address.
Depending on a condition, the value of State will = the value of Address. The problem I am having is maintaining a reference to State's previous value. I will need State's original value, should the condition change. As of now, my application cannot maintain a reference to old values.
Some more detail:
The data I am dealing with is Accounts and People (properties: Name, State, Address, Email) associated with these Accounts.
The data is displayed in a Matrix and the values are dependent on the aforementioned condition. The condition is which Account we are dealing with.
When there is a single Account, the value of State will = the value of Address. However, when there are more than 1 Accounts, the value of State will be unique.
The user can toggle between 4 Accounts. There can be multiple Accounts set at a time.
The problem is if I am dealing with a single Account and the State value becomes the Address value, I am not able to stash the old State value. The original State value will be used if there are more than 1 Account. When I have multiple Accounts, however, the State value is still = to the Address value. This is not ideal.
This is what I am looking for:
Example
Original Data = {"Ken, "WA", "123 St.", "Ken#email.com"}
Single Account
Name State Address Email
"Ken" "WA" "WA" "Ken#email.com"
Multiple Accounts
Name State Address Email
"Ken" "WA" "123 St." "Ken#email.com"
However, this is what I am getting:
Single Account - FINE
Name State Address Email
"Ken" "WA" "WA" "Ken#email.com"
Multiple Accounts - BAD
Name State Address Email
"Ken" "WA" "WA "Ken#email.com"
It is not cycling the value back
This is my code:
private void RefreshData()
{
List<string> states = new List<string>();
People.ForEach(p => states.Add(p.State)); // Attempting to stash current State vaues
bool singleAccount = Accounts.Where(a => a.IsActive).Count() == 1;
if (singleAccount)
{
int singleAccount = Accounts.IndexOf(Accounts.Where(a => a.IsActive).FirstOrDefault()) + 1; // Accounts are 1, 2, 3, or 4. I need the data for specific Account #s when a single Account
AssignStateToAddress(states, singleAccount);
}
else
{
// Use the original values here, since there are multiple Accounts.
}
}
private void AssignStateToAddress(List<string> States, int singleAccount)
{
int position = 0;
switch (singleAccount)
{
case 1: People.ForEach(p => p.Address1 = States[position++]);
break;
case 2: People.ForEach(p => p.Address2 = States[position++]);
break;
case 3: People.ForEach(p => p.Address3 = States[position++]);
break;
default: People.ForEach(p => p.Address4 = States[position++]);
break;
}
}
}
}
}
According to the OOP concept of encapsulation, this type of logic should probably be handled internally by your People class. There are several ways you could handle it, but probably the easiest is to make Address a method that understands the desired behavior.
public class People
{
public string State { get; set; }
private string _address;
public void SetAddress(string address)
=> _address = address;
public void GetAddress(bool forSingleAccount)
=> forSingleAccount ? State : _address;
}
This way "it just works" when you call GetAddress.
If you really need Address to be a property (for serialization, for example), then you can still encapsulate the behavior by adding an IsSingleAccount boolean property to People and make the Address getter check that and return one value or the other.
public class People
{
public bool IsSingleAccount { get; set; }
public string State { get; set; }
private string _address;
public string Address
{
set => _address = value;
get => IsSingleAccount ? State : _address;
}
}
That approach isn't as "clean" because People needs to track information about stuff that is an external concern, and your consuming code needs to go to extra steps to change that property on all instances. This is an example of a design problem known as a "leaky abstraction".
I have a User class that accumulates lots of DataTime entries in some List<DateTime> Entries field.
Occasionally, I need to get last 12 Entries (or less, if not reached to 12). It can get to very large numbers.
I can add new Entry object to dedicated collection, but then I have to add ObjectId User field to refer the related user.
It seems like a big overhead, for each entry that holds only a DateTime, to add another field of ObjectId. It may double the collection size.
As I occasionally need to quickly get only last 12 entries of 100,000 for instance, I cannot place these entries in a per-user collection like:
class PerUserEntries {
public ObjectId TheUser;
public List<DateTime> Entries;
}
Because it's not possible to fetch only N entries from an embedded array in a mongo query, AFAIK (if I'm wrong, it would be very gladdening!).
So am I doomed to double my collection size or is there a way around it?
Update, according to #profesor79's answer:
If your answer works, that will be perfect! but unfortunately it fails...
Since I needed to filter on the user entity as well, here is what I did:
With this data:
class EndUserRecordEx {
public ObjectId Id { get; set; }
public string UserName;
public List<EncounterData> Encounters
}
I am trying this:
var query = EuBatch.Find(u => u.UserName == endUser.UserName)
.Project<BsonDocument>(
Builders<EndUserRecordEx>.Projection.Slice(
u => u.Encounters, 0, 12));
var queryString = query.ToString();
var requests = await query.ToListAsync(); // MongoCommandException
This is the query I get in queryString:
find({ "UserName" : "qXyF2uxkcESCTk0zD93Sc+U5fdvUMPow" }, { "Encounters" : { "$slice" : [0, 15] } })
Here is the error (the MongoCommandException.Result):
{
{
"_t" : "OKMongoResponse",
"ok" : 0,
"code" : 9,
"errmsg" : "Syntax error, incorrect syntax near '17'.",
"$err" : "Syntax error, incorrect syntax near '17'."
}
}
Update: problem identified...
Recently, Microsoft announced their DocumentDB protocol support for MongoDB. Apparently, it doesn't support yet all projection operators. I tried it with mLab.com, and it works.
You can use PerUserEntries as this is a valuable document structure.
To get part of that array we need to add projection to query, so we can get only x elements and this is done server side.
Please see snippet below:
static void Main(string[] args)
{
// To directly connect to a single MongoDB server
// or use a connection string
var client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("test");
var collection = database.GetCollection<PerUserEntries>("tar");
var newData = new PerUserEntries();
newData.Entries = new List<DateTime>();
for (var i = 0; i < 1000; i++)
{
newData.Entries.Add(DateTime.Now.AddSeconds(i));
}
collection.InsertOne(newData);
var list =
collection.Find(new BsonDocument())
.Project<BsonDocument>
(Builders<PerUserEntries>.Projection.Slice(x => x.Entries, 0, 3))
.ToList();
Console.ReadLine();
}
public class PerUserEntries
{
public List<DateTime> Entries;
public ObjectId TheUser;
public ObjectId Id { get; set; }
}
I am implementing a integration with NetSuite in C#. In the external system I need to populate a list of countries that will match NetSuite's country list.
The NetSuite Web Service provides an enumeration call Country
public enum Country {
_afghanistan,
_alandIslands,
_albania,
_algeria,
...
You can also get a list of country Name and Code (in an albeit not so straight forward way) from the web service. (See: http://suiteweekly.com/2015/07/netsuite-get-all-country-list/)
Which gives you access to values like this:
Afghanistan, AF
Aland Islands, AX
Albania, AL
Algeria, DZ
American Samoa, AS
...
But, as you can see, there is no way to link the two together. (I tried to match by index but that didn't work and sounds scary anyway)
NetSuite's "help" files have a list. But this is static and I really want a dynamic solution that updates as NetSuites updates because we know countries will change--even is not that often.
Screenshot of Country Enumerations from NetSuite help docs
The only solutions I have found online are people who have provided static data that maps the two sets of data. (ex. suiteweekly.com /2015/07/netsuite-complete-country-list-in-netsuite/)
I cannot (don't want to) believe that this is the only solution.
Anyone else have experience with this that has a better solution?
NetSuite, if you are reading, come on guys, give a programmer a break.
The best solution I have come up with is to leverage the apparent relationship between the country name and the enumeration key to forge a link between the two. I am sure others could improve on this solution but what I would really like to see is a solution that isn't a hack like this that relies on an apparent pattern but rather on that is based on an explicit connection. Or better yet NetSuite should just provide the data in one place all together.
For example you can see the apparent relationship here:
_alandIslands -> Aland Islands
With a little code I can try to forge a match.
I first get the Enumeration Keys into an array. And I create a list of objects of type NetSuiteCountry that will hold my results.
var countryEnumKeys = Enum.GetNames(typeof(Country));
var countries = new List<NetSuiteCountry>();
I then loop through the list of country Name and Code I got using the referenced code above (not shown here).
For each country name I then strip all non-word characters from the country name with Regex.Replace, prepend an underscore (_) and then convert the string to lowercase. Finally I try to find a match between the Enumeration Key (converted to lowercase as well) and the matcher string that was created. If a match is found I save all the data together the countries list.
UPDATE: Based on the comments I have added additional code/hacks to try to deal with the anomalies without hard-coding exceptions. Hopefully these updates will catch any future updates to the country list as well, but no promises. As of this writing it was able to handle all the known anomalies. In my case I needed to ignore Deprecated countries so those aren't included.
foreach (RecordRef baseRef in baseRefList)
{
var name = baseRef.name;
//Skip Deprecated countries
if (name.EndsWith("(Deprecated)")) continue;
//Use the name to try to find and enumkey match and only add a country if found.
var enumMatcher = $"_{Regex.Replace(name, #"\W", "").ToLower()}";
//Compares Ignoring Case and Diacritic characters
var enumMatch = CountryEnumKeys.FirstOrDefault(e => string.Compare(e, enumMatcher, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreCase) == 0);
//Then try by Enum starts with Name but only one.
if (enumMatch == null)
{
var matches = CountryEnumKeys.Where(e => e.ToLower().StartsWith(enumMatcher));
if (matches.Count() == 1)
{
Debug.Write($"- Country Match Hack 1 : ");
enumMatch = matches.First();
}
}
//Then try by Name starts with Enum but only one.
if (enumMatch == null)
{
var matches = CountryEnumKeys.Where(e => enumMatcher.StartsWith(e.ToLower()));
if (matches.Count() == 1)
{
Debug.Write($"- Country Match Hack 2 : ");
enumMatch = matches.First();
}
}
//Finally try by first half Enum and Name match but again only one.
if (enumMatch == null)
{
var matches = CountryEnumKeys.Where(e => e.ToLower().StartsWith(enumMatcher.Substring(0, (enumMatcher.Length/2))));
if (matches.Count() == 1)
{
Debug.Write($"- Country Match Hack 3 : ");
enumMatch = matches.First();
}
}
if (enumMatch != null)
{
var enumIndex = Array.IndexOf(CountryEnumKeys, enumMatch);
if (enumIndex >= 0)
{
var country = (Country) enumIndex;
var nsCountry = new NetSuiteCountry
{
Name = baseRef.name,
Code = baseRef.internalId,
EnumKey = country.ToString(),
Country = country
};
Debug.WriteLine($"[{nsCountry.Name}] as [{nsCountry.EnumKey}]");
countries.Add(nsCountry);
}
}
else
{
Debug.WriteLine($"Could not find Country match for: [{name}] as [{enumMatcher}]");
}
}
Here is my NetSuiteCountry class:
public class NetSuiteCountry
{
public string Name { get; set; }
public string Code { get; set; }
public string EnumKey { get; set; }
public Country Country { get; set; }
}
Let me start off with a disclaimer that I'm not a coder, and this is the first day I've tried to look at a C# program.
I need something similar for a Javascript project where I need the complete list of Netsuite company names, codes and their numeric values and when reading the help it seemed like the only way was through webservices.
I downloaded the sample application for webservices from Netsuite and a version of Visual Studio and I was able to edit the sample program provided to create a list of all of the country names and country codes (ex. Canada, CA).
I started out doing something similar to the previous poster to get the list of country names:
string[] countryList = Enum.GetNames(typeof(Country));
foreach (string s in countryList)
{
_out.writeLn(s);
}
But I later got rid of this and started a new technique. I created a class similar to the previous answer:
public class NS_Country
{
public string countryCode { get; set; }
public string countryName { get; set; }
public string countryEnum { get; set; }
public string countryNumericID { get; set; }
}
Here is the new code for getting the list of company names, codes and IDs. I realize that it's not very efficient as I mentioned before I'm not really a coder and this is my first attempt with C#, lots of Google and cutting/pasting ;D.
_out.writeLn(" Attempting to get Country list.");
// Create a list for the NS_Country objects
List<NS_Country> CountryList = new List<NS_Country>();
// Create a new GetSelectValueFieldDescription object to use in a getSelectValue search
GetSelectValueFieldDescription countryDesc = new GetSelectValueFieldDescription();
countryDesc.recordType = RecordType.customer;
countryDesc.recordTypeSpecified = true;
countryDesc.sublist = "addressbooklist";
countryDesc.field = "country";
// Create a GetSelectValueResult object to hold the results of the search
GetSelectValueResult myResult = _service.getSelectValue(countryDesc, 0);
BaseRef[] baseRef = myResult.baseRefList;
foreach (BaseRef nsCountryRef in baseRef)
{
// Didn't know how to do this more efficiently
// Get the type for the BaseRef object, get the property for "internalId",
// then finally get it's value as string and assign it to myCountryCode
string myCountryCode = nsCountryRef.GetType().GetProperty("internalId").GetValue(nsCountryRef).ToString();
// Create a new NS_Country object
NS_Country countryToAdd = new NS_Country
{
countryCode = myCountryCode,
countryName = nsCountryRef.name,
// Call to a function to get the enum value based on the name
countryEnum = getCountryEnum(nsCountryRef.name)
};
try
{
// If the country enum was verified in the Countries enum
if (!String.IsNullOrEmpty(countryToAdd.countryEnum))
{
int countryEnumIndex = (int)Enum.Parse(typeof(Country), countryToAdd.countryEnum);
Debug.WriteLine("Enum: " + countryToAdd.countryEnum + ", Enum Index: " + countryEnumIndex);
_out.writeLn("ID: " + countryToAdd.countryCode + ", Name: " + countryToAdd.countryName + ", Enum: " + countryToAdd.countryEnum);
}
}
// There was a problem locating the country enum that was not handled
catch (Exception ex)
{
Debug.WriteLine("Enum: " + countryToAdd.countryEnum + ", Enum Index Not Found");
_out.writeLn("ID: " + countryToAdd.countryCode + ", Name: " + countryToAdd.countryName + ", Enum: Not Found");
}
// Add the countryToAdd object to the CountryList
CountryList.Add(countryToAdd);
}
// Create a JSON - I need this for my javascript
var javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string jsonString = javaScriptSerializer.Serialize(CountryList);
Debug.WriteLine(jsonString);
In order to get the enum values, I created a function called getCountryEnum:
static string getCountryEnum(string countryName)
{
// Create a dictionary for looking up the exceptions that can't be converted
// Don't know what Netsuite was thinking with these ones ;D
Dictionary<string, string> dictExceptions = new Dictionary<string, string>()
{
{"Congo, Democratic Republic of", "_congoDemocraticPeoplesRepublic"},
{"Myanmar (Burma)", "_myanmar"},
{"Wallis and Futuna", "_wallisAndFutunaIslands"}
};
// Replace with "'s" in the Country names with "s"
string countryName2 = Regex.Replace(countryName, #"\'s", "s");
// Call a function that replaces accented characters with non-accented equivalent
countryName2 = RemoveDiacritics(countryName2);
countryName2 = Regex.Replace(countryName2, #"\W", " ");
string[] separators = {" ","'"}; // "'" required to deal with country names like "Cote d'Ivoire"
string[] words = countryName2.Split(separators, StringSplitOptions.RemoveEmptyEntries);
for (var i = 0; i < words.Length; i++)
{
string word = words[i];
if (i == 0)
{
words[i] = char.ToLower(word[0]) + word.Substring(1);
}
else
{
words[i] = char.ToUpper(word[0]) + word.Substring(1);
}
}
string countryEnum2 = "_" + String.Join("", words);
// return an empty string if the country name contains Deprecated
bool b = countryName.Contains("Deprecated");
if (b)
{
return String.Empty;
}
else
{
// test to see if the country name was one of the exceptions
string test;
bool isExceptionCountry = dictExceptions.TryGetValue(countryName, out test);
if (isExceptionCountry == true)
{
return dictExceptions[countryName];
}
else
{
return countryEnum2;
}
}
}
In the above I used a function, RemoveDiacritics I found here. I will repost the referenced function below:
static string RemoveDiacritics(string text)
{
string formD = text.Normalize(NormalizationForm.FormD);
StringBuilder sb = new StringBuilder();
foreach (char ch in formD)
{
UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(ch);
if (uc != UnicodeCategory.NonSpacingMark)
{
sb.Append(ch);
}
}
return sb.ToString().Normalize(NormalizationForm.FormC);
}
Here are the tricky cases to test any solution you develop with:
// Test tricky names
Debug.WriteLine(getCountryEnum("Curaçao"));
Debug.WriteLine(getCountryEnum("Saint Barthélemy"));
Debug.WriteLine(getCountryEnum("Croatia/Hrvatska"));
Debug.WriteLine(getCountryEnum("Korea, Democratic People's Republic"));
Debug.WriteLine(getCountryEnum("US Minor Outlying Islands"));
Debug.WriteLine(getCountryEnum("Cote d'Ivoire"));
Debug.WriteLine(getCountryEnum("Heard and McDonald Islands"));
// Enums that fail
Debug.WriteLine(getCountryEnum("Congo, Democratic Republic of")); // _congoDemocraticPeoplesRepublic added to exceptions
Debug.WriteLine(getCountryEnum("Myanmar (Burma)")); // _myanmar added to exceptions
Debug.WriteLine(getCountryEnum("Netherlands Antilles (Deprecated)")); // Skip Deprecated
Debug.WriteLine(getCountryEnum("Serbia and Montenegro (Deprecated)")); // Skip Deprecated
Debug.WriteLine(getCountryEnum("Wallis and Futuna")); // _wallisAndFutunaIslands added to exceptions
For my purposes I wanted a JSON object that had all the values for Coutries (Name, Code, Enum, Value). I'll include it here in case anyone is searching for it. The numeric values are useful when you have a 3rd party HTML form that has to forward the information to a Netsuite online form.
Here is a link to the JSON object on Pastebin.
My appologies for the lack of programming knowledge (only really do a bit of javascript), hopefully this additional information will be useful for someone.
I have a class called Customer that has several string properties like
firstName, lastName, email, etc.
I read in the customer information from a csv file that creates an array of the class:
Customer[] customers
I need to remove the duplicate customers having the same email address, leaving only 1 customer record for each particular email address.
I have done this using 2 loops but it takes nearly 5 minutes as there are usually 50,000+ customer records. Once I am done removing the duplicates, I need to write the customer information to another csv file (no help needed here).
If I did a Distinct in a loop how would I remove the other string variables that are a part of the class for that particular customer as well?
Thanks,
Andrew
With Linq, you can do this in O(n) time (single level loop) with a GroupBy
var uniquePersons = persons.GroupBy(p => p.Email)
.Select(grp => grp.First())
.ToArray();
Update
A bit on O(n) behavior of GroupBy.
GroupBy is implemented in Linq (Enumerable.cs) as this -
The IEnumerable is iterated only once to create the grouping. A Hash of the key provided (e.g. "Email" here) is used to find unique keys, and the elements are added in the Grouping corresponding to the keys.
Please see this GetGrouping code. And some old posts for reference.
What's the asymptotic complexity of GroupBy operation?
What guarantees are there on the run-time complexity (Big-O) of LINQ methods?
Then Select is obviously an O(n) code, making the above code O(n) overall.
Update 2
To handle empty/null values.
So, if there are instances where the value of Email is null or empty, the simple GroupBy will take just one of those objects from null & empty each.
One quick way to include all those objects with null/empty value is to use some unique keys at the run time for those objects, like
var tempEmailIndex = 0;
var uniqueNullAndEmpty = persons
.GroupBy(p => string.IsNullOrEmpty(p.Email)
? (++tempEmailIndex).ToString() : p.Email)
.Select(grp => grp.First())
.ToArray();
I'd do it like this:
public class Person {
public Person(string eMail, string Name) {
this.eMail = eMail;
this.Name = Name;
}
public string eMail { get; set; }
public string Name { get; set; }
}
public class eMailKeyedCollection : System.Collections.ObjectModel.KeyedCollection<string, Person> {
protected override string GetKeyForItem(Person item) {
return item.eMail;
}
}
public void testIt() {
var testArr = new Person[5];
testArr[0] = new Person("Jon#Mullen.com", "Jon Mullen");
testArr[1] = new Person("Jane#Cullen.com", "Jane Cullen");
testArr[2] = new Person("Jon#Cullen.com", "Jon Cullen");
testArr[3] = new Person("John#Mullen.com", "John Mullen");
testArr[4] = new Person("Jon#Mullen.com", "Test Other"); //same eMail as index 0...
var targetList = new eMailKeyedCollection();
foreach (var p in testArr) {
if (!targetList.Contains(p.eMail))
targetList.Add(p);
}
}
If the item is found in the collection, you could easily pick (and eventually modify) it with:
if (!targetList.Contains(p.eMail))
targetList.Add(p);
else {
var currentPerson=targetList[p.eMail];
//modify Name, Address whatever...
}
Okay, here's what I'm attempting.
I have a drop down list with all of the countries in the world.
The user selects one, and that value is passed to a case statement,
if it matches the case, an email is sent.
I only have four different recipents, but I can have upwards to dozens
of countries to match with each one of the four emails. For example:
switch (selectedCountry)
{
case "ca":
sendTo = canadaEmail;
break;
case "uk":
case "de":
case "fr"
sendTo = europeanEmail;
break;
case "bb":
sendTo = barbadosEmail;
break;
default:
sendTo = usEmail;
break;
}
What I would like to know is, what's a better way of doing this rather than having
one huge case statement?
You can use a dictionary instead:
Dictionary<string, string> sendToEmails = new Dictionary<string, string>();
sendToEmails["bb"] = barbadosEmail;
sendToEmails["ca"] = canadaEmail;
sendToEmails["uk"] = europeanEmail;
sendToEmails["de"] = europeanEmail;
Then use TryGetValue to get the value when you need it:
string sendTo;
if (sendToEmails.TryGetValue(selectedCountry, out sendTo))
{
// Send the email here.
}
One advantage of this method is that your dictionary doesn't have to be hard coded into your program. It could just as easily come from a configuration file or a database.
If you choose the database route you could also consider using LINQ:
string sendTo = dc.CountryEmails
.SingleOrDefault(c => c.Country == selectedCountry);
You can't get around the fact that somewhere, somehow, you'll have to enumerate the countries and assign them to an email address. You could do that in any number of ways, be it a database, an external XML file, or an internal List object.
For example:
List<string> europeanEmailCountries = new List<string>();
europeanEmailCountries.AddRange("fr", "de"); // etc
...
if(europeanEmailCountries.Contains(countryCode))
{
sendTo = europeanEmailAddress;
}
This saves you the convoluted switch statement by allowing you to define a list of countries mapped to a particular email address, without going through each potential entry. I might be inclined to populate the list from an XML file instead of hardcoding the values, though.
A couple options that would eliminate the cases:
Store the mappings in a database and look them up by country code.
Build a map in your code with the country code as the key and the email as the value.
Externalize it (XML, database, whatever you like...) and only implement a "state machine" which chooses the right one.
Yes -- if you have a hard coded list somewhere, consider using a collection of a custom type:
public class MyType
{
public string Code { get; set; }
public string Email { get; set; }
}
Then you could do something like this:
List<MyType> myList = new List<MyType>()
{
new MyType() { Code = "A", Email = "something" },
// etc..
}
string emailAddress = myList.Where(m => m.Code == selectedCountry);
Although, I'd say this is very poor design and I would encourage you to use a rdbms of some sort.