本文整理汇总了C#中System.Collections.Dictionary.FirstOrDefault方法的典型用法代码示例。如果您正苦于以下问题:C# Dictionary.FirstOrDefault方法的具体用法?C# Dictionary.FirstOrDefault怎么用?C# Dictionary.FirstOrDefault使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Collections.Dictionary
的用法示例。
在下文中一共展示了Dictionary.FirstOrDefault方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: DradisForm
public DradisForm(MainForm parent)
{
InitializeComponent();
this.parent = parent;
_sectors = new Dictionary<ListBox, DeckManager.Boards.Dradis.DradisNodeName>();
_sectors.Add(alphaListBox, DeckManager.Boards.Dradis.DradisNodeName.Alpha);
_sectors.Add(bravoListBox, DeckManager.Boards.Dradis.DradisNodeName.Bravo);
_sectors.Add(charlieListBox, DeckManager.Boards.Dradis.DradisNodeName.Charlie);
_sectors.Add(deltaListBox, DeckManager.Boards.Dradis.DradisNodeName.Delta);
_sectors.Add(echoListBox, DeckManager.Boards.Dradis.DradisNodeName.Echo);
_sectors.Add(foxtrotListBox, DeckManager.Boards.Dradis.DradisNodeName.Foxtrot);
foreach (DeckManager.Boards.Dradis.DradisNode node in Program.GManager.CurrentGameState.Dradis.Nodes)
{
ListBox sector = _sectors.FirstOrDefault(x => x.Value == node.Name).Key;
sector.Items.AddRange(node.Components.ToArray());
}
var values = Enum.GetValues(typeof(DeckManager.Components.Enums.ComponentType));
foreach (DeckManager.Components.Enums.ComponentType type in values)
{
if (type == DeckManager.Components.Enums.ComponentType.Unknown)
continue;
this.LaunchComponentComboBox.Items.Add(type);
}
values = Enum.GetValues(typeof(DeckManager.Boards.Dradis.DradisNodeName));
foreach (DeckManager.Boards.Dradis.DradisNodeName sector in values)
{
if (sector == DeckManager.Boards.Dradis.DradisNodeName.Unknown)
continue;
this.LaunchLocationComboBox.Items.Add(sector);
}
}
示例2: Max
//Given a sequence of non-negative integers find a subsequence of length 3 having maximum product with the numbers of the subsequence being in ascending order.
//Example:
//Input: 6 7 8 1 2 3 9 10
//Ouput: 8 9 10
//Wrong!!!
public List<int> Max(int[] a)
{
Dictionary<List<int>, int> result = new Dictionary<List<int>, int>();
List<int> list = new List<int>();
list.Add(a[0]);
result.Add(list, a[0]);
int max = 0, min = 0;
for (int i = 1; i < a.Length; i++)
{
min = result.Values.Min();
max = result.Values.Max();
if (a[i] >= max)
{
list = result.FirstOrDefault(x => x.Value == max).Key;
list.Add(a[i]);
result[list] = a[i];
if (list.Count > 3)
list.RemoveAt(0);
}
else if (a[i] <= min)
{
list = new List<int>();
list.Add(a[i]);
result.Add(list, a[i]);
}
else
{
for(int x=0;x<result.Count;x++)
{
var t = result.ElementAt(x);
if (t.Value < a[i])
{
t.Key.Add(a[i]);
result[t.Key] = a[i];
if (t.Key.Count > 3)
t.Key.RemoveAt(0);
}
}
}
}
max = result.Values.Max();
list = result.FirstOrDefault(x => x.Value == max).Key;
return list;
}
示例3: Both_have_same
internal static string Both_have_same(string[] master, string[] slave)
{
string[] tmpMaster = new string[5];
string[] tmpSlave = new string[5];
int[] tmpMasterInt = new int[5];
int[] tmpSlaveInt = new int[5];
for (int i = 0; i < 5; i++)
{
tmpMaster[i] = master[i].Remove(master[i].Length - 1);
tmpSlave[i] = slave[i].Remove(slave[i].Length - 1);
}
for (int i = 0; i < 5; i++)
{
if (tmpMaster[i] == "A") tmpMasterInt[i] = 14;
else if (tmpMaster[i] == "K") tmpMasterInt[i] = 13;
else if (tmpMaster[i] == "Q") tmpMasterInt[i] = 12;
else if (tmpMaster[i] == "J") tmpMasterInt[i] = 11;
else
{
Int32.TryParse(tmpMaster[i], out tmpMasterInt[i]);
}
}
for (int i = 0; i < 5; i++)
{
if (tmpSlave[i] == "A") tmpSlaveInt[i] = 14;
else if (tmpSlave[i] == "K") tmpSlaveInt[i] = 13;
else if (tmpSlave[i] == "Q") tmpSlaveInt[i] = 12;
else if (tmpSlave[i] == "J") tmpSlaveInt[i] = 11;
else
{
Int32.TryParse(tmpSlave[i], out tmpSlaveInt[i]);
}
}
Dictionary<int, int> dic_m = new Dictionary<int, int>();
foreach (int num in tmpMasterInt)
{
if (dic_m.ContainsKey(num))
{
dic_m[num] += 1;
}
else
{
dic_m.Add(num,1);
}
}
Dictionary<int, int> dic_s = new Dictionary<int, int>();
foreach (int num in tmpSlaveInt)
{
if (dic_s.ContainsKey(num))
{
dic_s[num] += 1;
}
else
{
dic_s.Add(num, 1);
}
}
if (dic_m.Count == 4)
{
int m = dic_m.FirstOrDefault(x => x.Value == 2).Key;
int s = dic_s.FirstOrDefault(x => x.Value == 2).Key;
if (m > s) return "m";
else if (m < s) return "s";
else return "n";
}
else if (dic_m.Count == 3)
{
int m = dic_m.FirstOrDefault(x => x.Value == 3).Key;
int s = dic_s.FirstOrDefault(x => x.Value == 3).Key;
if (m > s) return "m";
else if (m < s) return "s";
else return "n";
}
else if (dic_m.Count == 2)
{
int m = dic_m.FirstOrDefault(x => x.Value == 4).Key;
int s = dic_s.FirstOrDefault(x => x.Value == 4).Key;
if (m > s) return "m";
else if (m < s) return "s";
else return "n";
}
else return "n";
}
示例4: GetEqualValues
private static ValuesType GetEqualValues(ValuesType originalValues, Dictionary<ValuesType, ValuesType> variableValuesMapping) {
if (variableValuesMapping.ContainsKey(originalValues)) return variableValuesMapping[originalValues];
var matchingValues = variableValuesMapping.FirstOrDefault(kv => kv.Key == kv.Value && EqualVariableValues(originalValues, kv.Key)).Key ?? originalValues;
variableValuesMapping[originalValues] = matchingValues;
return matchingValues;
}
示例5: OutAAProgram
//.........这里部分代码省略.........
finalTrans.data.ExpTypes[fieldRef3Exp] =
//finalTrans.data.ExpTypes[fieldRef4Exp] =
finalTrans.data.ExpTypes[assignment] = field.GetType();
finalTrans.data.ExpTypes[nullExp1] =
finalTrans.data.ExpTypes[nullExp2] =
/*finalTrans.data.ExpTypes[nullExp3] =*/ new ANamedType(new TIdentifier("null"), null);
finalTrans.data.ExpTypes[binop1] =
/*finalTrans.data.ExpTypes[binop2] = */new ANamedType(new TIdentifier("bool"), null);
fieldMethods[field] = method;
}
/* AFieldLvalue fieldRef = new AFieldLvalue(new TIdentifier(field.GetName().Text, token.Line, token.Pos));
finalTrans.data.FieldLinks[fieldRef] = field;*/
//stringExp.ReplaceBy(new ALvalueExp(fieldRef));
}
ASimpleInvokeExp invoke2 =
new ASimpleInvokeExp(new TIdentifier(fieldMethods[field].GetName().Text), new ArrayList());
finalTrans.data.SimpleMethodLinks[invoke2] = fieldMethods[field];
stringExp.ReplaceBy(invoke2);
//If we are in a field, move it in
if (Util.GetAncestor<AFieldDecl>(invoke2) != null)
moveFieldsIn.Add(Util.GetAncestor<AFieldDecl>(invoke2));
}
}
foreach (AFieldDecl field in finalTrans.data.ObfuscationFields)
{
if (field.GetInit() == null && field.Parent() != null)
{
field.Parent().RemoveChild(field);
}
}
//A constant field, or a field used by a constant field cannot be moved in
List<AFieldDecl> constantFields = new List<AFieldDecl>();
foreach (SharedData.DeclItem<AFieldDecl> field in finalTrans.data.Fields)
{
if (field.Decl.GetConst() != null)
constantFields.Add(field.Decl);
}
for (int i = 0; i < constantFields.Count; i++)
{
GetFieldLvalues lvalues = new GetFieldLvalues();
constantFields[i].Apply(lvalues);
foreach (AFieldLvalue lvalue in lvalues.Lvalues)
{
AFieldDecl field = finalTrans.data.FieldLinks[lvalue];
if (!constantFields.Contains(field))
constantFields.Add(field);
}
}
moveFieldsIn.RemoveAll(constantFields.Contains);
Dictionary<AFieldDecl, List<AFieldDecl>> dependancies = new Dictionary<AFieldDecl, List<AFieldDecl>>();
//Order the fields so any dependancies are instansiated first
foreach (AFieldDecl field in moveFieldsIn)
{
dependancies.Add(field, new List<AFieldDecl>());
GetFieldLvalues lvalues = new GetFieldLvalues();
field.Apply(lvalues);
foreach (AFieldLvalue lvalue in lvalues.Lvalues)
{
AFieldDecl dependancy = finalTrans.data.FieldLinks[lvalue];
if (!dependancies[field].Contains(dependancy))
dependancies[field].Add(dependancy);
}
}
List<PStm> newStatements = new List<PStm>();
while (dependancies.Keys.Count > 0)
{
AFieldDecl field = dependancies.FirstOrDefault(f1 => f1.Value.Count == 0).Key ??
dependancies.Keys.First(f => true);
AFieldLvalue fieldRef = new AFieldLvalue(new TIdentifier(field.GetName().Text));
AAssignmentExp assignment = new AAssignmentExp(new TAssign("="), fieldRef, field.GetInit());
field.SetInit(null);
newStatements.Add(new AExpStm(new TSemicolon(";"), assignment));
finalTrans.data.FieldLinks[fieldRef] = field;
finalTrans.data.LvalueTypes[fieldRef] =
finalTrans.data.ExpTypes[assignment] = field.GetType();
foreach (KeyValuePair<AFieldDecl, List<AFieldDecl>> dependancy in dependancies)
{
if (dependancy.Value.Contains(field))
dependancy.Value.Remove(field);
}
dependancies.Remove(field);
}
AABlock initBody = (AABlock) finalTrans.mainEntry.GetBlock();
for (int i = newStatements.Count - 1; i >= 0; i--)
{
initBody.GetStatements().Insert(0, newStatements[i]);
}
}
示例6: GetConfigValueFromPrivateConfig
/// <summary>
/// Get the private config value for a specific attribute.
/// The private config looks like this:
/// XML:
/// <PrivateConfig xmlns="namespace">
/// <StorageAccount name = "name" key="key" endpoint="endpoint" />
/// <EventHub Url = "url" SharedAccessKeyName="sasKeyName" SharedAccessKey="sasKey"/>
/// </PrivateConfig>
///
/// JSON:
/// "PrivateConfig":{
/// "storageAccountName":"name",
/// "storageAccountKey":"key",
/// "storageAccountEndPoint":"endpoint",
/// "EventHub":{
/// "Url":"url",
/// "SharedAccessKeyName":"sasKeyName",
/// "SharedAccessKey":"sasKey"
/// }
/// }
/// </summary>
/// <param name="configurationPath">The path to the configuration file</param>
/// <param name="elementName">The element name of the private config. e.g., StorageAccount, EventHub</param>
/// <param name="attributeName">The attribute name of the element</param>
/// <returns></returns>
public static string GetConfigValueFromPrivateConfig(string configurationPath, string elementName, string attributeName)
{
string value = string.Empty;
var configFileType = GetConfigFileType(configurationPath);
if (configFileType == ConfigFileType.Xml)
{
var xmlConfig = XElement.Load(configurationPath);
if (xmlConfig.Name.LocalName == DiagnosticsConfigurationElemStr)
{
var privateConfigElem = xmlConfig.Elements().FirstOrDefault(ele => ele.Name.LocalName == PrivateConfigElemStr);
var configElem = privateConfigElem == null ? null : privateConfigElem.Elements().FirstOrDefault(ele => ele.Name.LocalName == elementName);
var attribute = configElem == null ? null : configElem.Attributes().FirstOrDefault(a => string.Equals(a.Name.LocalName, attributeName));
value = attribute == null ? null : attribute.Value;
}
}
else if (configFileType == ConfigFileType.Json)
{
// Find the PrivateConfig
var jsonConfig = JsonConvert.DeserializeObject<JObject>(File.ReadAllText(configurationPath));
var properties = jsonConfig.Properties().Select(p => p.Name);
var privateConfigProperty = properties.FirstOrDefault(p => p.Equals(PrivateConfigElemStr));
if (privateConfigProperty == null)
{
return value;
}
var privateConfig = jsonConfig[privateConfigProperty] as JObject;
// Find the target config object corresponding to elementName
JObject targetConfig = null;
if (elementName == StorageAccountElemStr)
{
// Special handling as private storage config is flattened
targetConfig = privateConfig;
var attributeNameMapping = new Dictionary<string, string>()
{
{ PrivConfNameAttr, "storageAccountName" },
{ PrivConfKeyAttr, "storageAccountKey" },
{ PrivConfEndpointAttr, "storageAccountEndPoint" }
};
attributeName = attributeNameMapping.FirstOrDefault(m => m.Key == attributeName).Value;
}
else
{
properties = privateConfig.Properties().Select(p => p.Name);
var configProperty = properties.FirstOrDefault(p => p.Equals(elementName));
targetConfig = configProperty == null ? null : privateConfig[configProperty] as JObject;
}
if (targetConfig == null || attributeName == null)
{
return value;
}
// Find the config value corresponding to attributeName
properties = targetConfig.Properties().Select(p => p.Name);
var attributeProperty = properties.FirstOrDefault(p => p.Equals(attributeName));
value = attributeProperty == null ? null : targetConfig[attributeProperty].Value<string>();
}
return value;
}
示例7: Convert
public bool Convert(ProgressBar progressBar = null)
{
if (progressBar != null) {
progressBar.Value = 0;
}
int AppealIndex = 1;
// Запоминаем текущую дату и время, чтобы установить их всем создаваемым обращениям.
this.ConvertDate = DateTime.Now;
// Находим заявителей с фиктивным ID и создаём их.
Dictionary<string, string> FakeToReal = new Dictionary<string, string>();
foreach (Declarant d in Declarants) {
if (d.GetID().Contains("fake-")) {
string FakeID = d.GetID();
string RealID = "";
try {
RealID = d.SaveToDB(this.ConvertDate);
FakeToReal.Add(FakeID, RealID);
} catch (Exception e) {
e.Data.Add("UserMessage", "Заявитель: " + d.GetFIO());
DB.Rollback();
throw;
}
this.Log("cat_declarants", RealID);
}
}
// Записываем обращения в БД
foreach (Appeal NewAppeal in this.SimpleAppeals) {
// Заменяем фиктивные id заявителей на реальные.
for(int i = 0; i < NewAppeal.multi.Count; i++) {
string[] str = (string[]) NewAppeal.multi[i];
if (str[0] == "declarant") {
KeyValuePair<string, string> ids = FakeToReal.FirstOrDefault(x => x.Key == str[1]);
if (ids.Value != null && ids.Value != "") {
((string[])NewAppeal.multi[i])[1] = ids.Value;
//NewAppeal.multi[i] = new string[] { "declarant", ids.Value, str[2] };
}
}
}
try {
CreateAppeal(NewAppeal);
} catch (Exception e) {
e.Data.Add("UserMessage", "Заявка: " + NewAppeal.numb);
DB.Rollback();
throw;
}
if (progressBar != null) {
double percent = (double)AppealIndex / this.SimpleAppeals.Count * 100;
progressBar.Value = System.Convert.ToInt32(percent);
}
AppealIndex++;
}
LinkAppeals();
DB.Commit();
return true;
}
示例8: ParaTextDcLanguage
/// <summary>
/// Get the LangCode from the Database.ssf file and insert it in css file
/// </summary>
public static string ParaTextDcLanguage(string dataBaseName, bool hyphenlang)
{
string dcLanguage = string.Empty;
if (AppDomain.CurrentDomain.FriendlyName.ToLower() == "paratext.exe") // is paratext00
{
// read Language Code from ssf
SettingsHelper settingsHelper = new SettingsHelper(dataBaseName);
string fileName = settingsHelper.GetSettingsFilename();
string xPath = "//ScriptureText/EthnologueCode";
XmlNode xmlLangCode = GetXmlNode(fileName, xPath);
if (xmlLangCode != null && xmlLangCode.InnerText != string.Empty)
{
dcLanguage = xmlLangCode.InnerText;
}
xPath = "//ScriptureText/Language";
XmlNode xmlLangNameNode = GetXmlNode(fileName, xPath);
if (xmlLangNameNode != null && xmlLangNameNode.InnerText != string.Empty)
{
if (dcLanguage == string.Empty)
{
Dictionary<string, string> _languageCodes = new Dictionary<string, string>();
_languageCodes = LanguageCodesfromXMLFile();
if (_languageCodes.Count > 0)
{
foreach (
var languageCode in
_languageCodes.Where(
languageCode => languageCode.Value.ToLower() == xmlLangNameNode.InnerText.ToLower()))
{
if (hyphenlang)
{
dcLanguage = _languageCodes.ContainsValue(languageCode.Key.ToLower())
? _languageCodes.FirstOrDefault(x => x.Value == languageCode.Key.ToLower()).Key
: languageCode.Key;
}
else
{
dcLanguage = languageCode.Key;
}
break;
}
}
}
dcLanguage += ":" + xmlLangNameNode.InnerText;
}
}
return dcLanguage;
}
示例9: GenerateList
private static IEnumerable<IList<Expression>> GenerateList(Dictionary<Expression, IEnumerable<object>> elements, IList<Expression> list) {
Contract.Requires(elements != null);
var tmp = list ?? new List<Expression>();
var kvp = elements.FirstOrDefault();
if (kvp.Equals(default(KeyValuePair<Expression, IEnumerable<Object>>))) {
if (list != null)
yield return list;
else {
yield return new List<Expression>();
}
} else {
elements.Remove(kvp.Key);
foreach (var result in kvp.Value) {
var resultExpr = result is IVariable ? Util.VariableToExpression(result as IVariable) : result as Expression;
tmp.Add(resultExpr);
foreach (var value in GenerateList(elements, tmp)) {
yield return value;
}
}
}
}
示例10: GetDuplicateSubscribers
// ------------------------------------------------------------
// Name: UpdateConvertedProspects
// Abstract: Retrieve subscribers from a list
// ------------------------------------------------------------
public static Dictionary<string, string> GetDuplicateSubscribers()
{
Dictionary<string, string> dctDuplicateSubscribers = new Dictionary<string, string>();
Dictionary<string, string> dctSubscribers = new Dictionary<string, string>();
Dictionary<string, string> dctAllSubscribers = new Dictionary<string, string>();
try
{
string strCustomerNumber = "";
string strSubscriberKey = "";
string strEmail = "";
// Get subscriber dates
ET_Subscriber getSub = new ET_Subscriber();
getSub.AuthStub = m_etcTDClient;
getSub.Props = new string[] { "SubscriberKey", "EmailAddress" };
GetReturn getResponse = getSub.Get();
Console.WriteLine("Get Status: " + getResponse.Status.ToString());
Console.WriteLine("Message: " + getResponse.Message.ToString());
Console.WriteLine("Code: " + getResponse.Code.ToString());
Console.WriteLine("Results Length: " + getResponse.Results.Length);
while (getResponse.MoreResults == true)
{
foreach (ET_Subscriber sub in getResponse.Results)
{
Console.WriteLine("SubscriberKey: " + sub.SubscriberKey);
// Add to our list
dctAllSubscribers.Add(sub.SubscriberKey, sub.EmailAddress);
}
getResponse = getSub.GetMoreResults();
}
foreach (KeyValuePair<string, string> entry in dctAllSubscribers)
{
strSubscriberKey = entry.Key;
strEmail = entry.Value;
// Add to duplicates if email already exists
if (dctSubscribers.ContainsValue(strEmail) == true)
{
// Get customer number from duplicate if duplicate hasn't been logged
if (dctDuplicateSubscribers.ContainsValue(strEmail) == false)
{
strCustomerNumber = dctSubscribers.FirstOrDefault(x => x.Value == strEmail).Key;
// Add (both) duplicate entries
dctDuplicateSubscribers.Add(strSubscriberKey, strEmail);
dctDuplicateSubscribers.Add(strCustomerNumber, strEmail);
}
else
{
dctDuplicateSubscribers.Add(strSubscriberKey, strEmail);
}
}
else
{
// Add to our list
dctSubscribers.Add(strSubscriberKey, strEmail);
}
}
}
catch (Exception excError)
{
// Display Error
Console.WriteLine("Error: " + excError.ToString());
}
return dctDuplicateSubscribers;
}
示例11: Main
static void Main(string[] args)
{
{
C[] tableC = new C[10];
Array.ForEach(tableC, c => { c = new C(); });
Console.WriteLine("Objects Created ");
Console.WriteLine("Press enter to Destroy it");
Console.ReadLine();
//Array.ForEach(tableC, c => { c = null; });
tableC = null;
Console.WriteLine("Call GC.Collect");
GC.Collect();
}
//Test codes
int spaceX = 0, spaceY = 0;
Dictionary<int, int> mts = new Dictionary<int, int>();
//mts.Any(k => { return k.Key == iTest && Math.Abs(k.Value - iTest) == 1; });
bool isApproach = mts.Any(
p =>
{
bool isApproachNow = ((p.Key == spaceX));
if (isApproachNow == true)
{
var nextL = mts.FirstOrDefault(p_ => { return (spaceY - p_.Value) <= 1; });
if (nextL.Equals(default(KeyValuePair<int, int>)) == true)
{
return true;
}
else
{
return nextL.Key == spaceX;
}
}
else
{
return false;
}
});
//Any routines for call Object destructors.
Console.Read();
//Console.ReadLine();
int n = int.Parse(Console.ReadLine()); // the number of temperatures to analyse
string temps = Console.ReadLine(); // the n temperatures expressed as integers ranging from -273 to 5526
// Write an action using Console.WriteLine()
// To debug: Console.Error.WriteLine("Debug messages...");
string[] tempsStr = temps.Split(' ');
int[] tempsNum = new int[tempsStr.Count()];
string.IsNullOrEmpty(temps);
int tempNearst = tempsNum[0];
foreach (int temp in tempsNum)
{
int tnAbs = Math.Abs(tempNearst), tAbs = Math.Abs(temp);
if (tnAbs == tAbs)
{
tempNearst = (temp > 0) ? temp : tempNearst;
}
else if (tnAbs > tAbs)
{
tempNearst = temp;
}
}
//string outputDebug = "";
//for (int i = 0; i < 10; ++i)
//{
// outputDebug = outputDebug + "\nNumber:" + i;
//}
//System.Diagnostics.Trace.WriteLine(outputDebug);
}
示例12: Add
// Adds item control to a group
// (this item control will only be allowed to participate in d&d in this particular gorup)
private static void Add(Dictionary<String, List<ItemsControl>> dictionary, object sender)
{
InitializeDragDropCollections();
var dp = sender as DependencyObject;
var itemsControl = sender as ItemsControl;
var groupName = GetGroupName(dp);
var foundGroup = dictionary.FirstOrDefault(p => p.Key == groupName);
if (!foundGroup.Value.Contains(itemsControl))
dictionary[groupName].Add(itemsControl);
itemsControl.Unloaded += DropTarget_Unloaded;
itemsControl.Loaded += DropTarget_Loaded;
}
示例13: Remove
// Removes item control from group
private static void Remove(Dictionary<String, List<ItemsControl>> dictionary, object sender)
{
var dp = sender as DependencyObject;
var itemsControl = sender as ItemsControl;
var groupName = GetGroupName(dp);
var foundGroup = dictionary.FirstOrDefault(p => p.Key == groupName);
if (foundGroup.Value.Contains(itemsControl))
dictionary[groupName].Remove(itemsControl);
itemsControl.Unloaded -= DropTarget_Unloaded;
itemsControl.Loaded -= DropTarget_Loaded;
}
示例14: GetState
public static string GetState(string abbr = null, string state = null)
{
Dictionary<string, string> states = new Dictionary<string, string>();
states.Add("AL", "alabama");
states.Add("AK", "alaska");
states.Add("AZ", "arizona");
states.Add("AR", "arkansas");
states.Add("CA", "california");
states.Add("CO", "colorado");
states.Add("CT", "connecticut");
states.Add("DE", "delaware");
states.Add("DC", "district of columbia");
states.Add("FL", "florida");
states.Add("GA", "georgia");
states.Add("HI", "hawaii");
states.Add("ID", "idaho");
states.Add("IL", "illinois");
states.Add("IN", "indiana");
states.Add("IA", "iowa");
states.Add("KS", "kansas");
states.Add("KY", "kentucky");
states.Add("LA", "louisiana");
states.Add("ME", "maine");
states.Add("MD", "maryland");
states.Add("MA", "massachusetts");
states.Add("MI", "michigan");
states.Add("MN", "minnesota");
states.Add("MS", "mississippi");
states.Add("MO", "missouri");
states.Add("MT", "montana");
states.Add("NE", "nebraska");
states.Add("NV", "nevada");
states.Add("NH", "new hampshire");
states.Add("NJ", "new jersey");
states.Add("NM", "new mexico");
states.Add("NY", "new york");
states.Add("NC", "north carolina");
states.Add("ND", "north dakota");
states.Add("OH", "ohio");
states.Add("OK", "oklahoma");
states.Add("OR", "oregon");
states.Add("PA", "pennsylvania");
states.Add("RI", "rhode island");
states.Add("SC", "south carolina");
states.Add("SD", "south dakota");
states.Add("TN", "tennessee");
states.Add("TX", "texas");
states.Add("UT", "utah");
states.Add("VT", "vermont");
states.Add("VA", "virginia");
states.Add("WA", "washington");
states.Add("WV", "west virginia");
states.Add("WI", "wisconsin");
states.Add("WY", "wyoming");
if (abbr != null && states.ContainsKey(abbr.ToUpper()))
return (states[abbr.ToUpper()]);
if (state != null && states.Values.Contains(state.ToLower()))
return states.FirstOrDefault(x => x.Value == state).Key;
/* error handler is to return an empty string rather than throwing an exception */
return "";
}