本文整理汇总了C#中Dictionary.FirstOrDefault方法的典型用法代码示例。如果您正苦于以下问题:C# Dictionary.FirstOrDefault方法的具体用法?C# Dictionary.FirstOrDefault怎么用?C# Dictionary.FirstOrDefault使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Dictionary
的用法示例。
在下文中一共展示了Dictionary.FirstOrDefault方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: oldestYoungest
public static void oldestYoungest(Dictionary<string, int> friendList)
{
Console.WriteLine("{0} is the oldest friend,\n{1} is the youngest friend.",
friendList.FirstOrDefault(x => x.Value == friendList.Values.Max()).Key,
friendList.FirstOrDefault(x => x.Value == friendList.Values.Min()).Key
);
}
示例2: Get
public static string Get(Dictionary<string, string> dict, FormatType formatType, string code)
{
if (formatType == FormatType.GetKey)
return dict.FirstOrDefault(d => d.Value == code).Key;
else
return dict.FirstOrDefault(d => d.Key == code).Value;
}
示例3: IsPlayersTurn
public static bool IsPlayersTurn(Dictionary<int, Entity> entities)
{
var firstPlayer = entities.FirstOrDefault(e => e.Value.HasTag(FIRST_PLAYER)).Value;
if(firstPlayer != null)
{
var offset = firstPlayer.IsPlayer ? 0 : 1;
var gameRoot = entities.FirstOrDefault(e => e.Value != null && e.Value.Name == "GameEntity").Value;
if(gameRoot != null)
return (gameRoot.Tags[TURN] + offset) % 2 == 1;
}
return false;
}
示例4: TopSort
//working tests
public ICollection<string> TopSort()
{
Dictionary<string, int> predecessors = new Dictionary<string, int>();
foreach (var vertexEdgesPair in this.graph)
{
if (!predecessors.ContainsKey(vertexEdgesPair.Key))
{
predecessors[vertexEdgesPair.Key] = 0;
}
foreach (string child in vertexEdgesPair.Value)
{
if (!predecessors.ContainsKey(child))
{
predecessors[child] = 0;
}
predecessors[child]++;
}
}
var result = new List<string>();
string nextNode = predecessors.FirstOrDefault(vertexEdgesPair => vertexEdgesPair.Value == 0).Key;
while (nextNode != null)
{
result.Add(nextNode);
if (this.graph.ContainsKey(nextNode))
{
foreach (string child in this.graph[nextNode])
{
predecessors[child]--;
}
}
predecessors.Remove(nextNode);
nextNode = predecessors.FirstOrDefault(vertexEdgesPair => vertexEdgesPair.Value == 0).Key;
}
bool graphIsCyclic = predecessors.Count > 0;
if (graphIsCyclic)
{
throw new InvalidOperationException("A cycle detected in the graph");
}
return result;
}
示例5: GetPopupContent
/// <summary>
/// Gets the hierarcchical row that describes the selected feature
/// </summary>
/// <param name="selectedFeatures"></param>
/// <returns></returns>
public async Task<List<PopupContent>> GetPopupContent(Dictionary<BasicFeatureLayer, List<long>> selectedFeatures)
{
//_layersInMapFeatureClassMap = GetMapLayersFeatureClassMap(); //gets all the feature layers from the map and add it to the dictionary with the Feature class as its key
var popupContents = new List<PopupContent>();
try
{
var objectIDS = _selection.GetObjectIDs();
if (_geodatabase == null)
_geodatabase = await GetGDBFromLyrAsync(_featureLayer);
var kvpMapMember = selectedFeatures.FirstOrDefault(s => s.Key.GetTable().GetName().Equals(_featureClassName));
foreach (var objectID in objectIDS)
{
//List<HierarchyRow> hrows = new List<HierarchyRow>(); //this makes the custom popup show only one record.
//var newRow = await GetRelationshipChildren(_featureClassName, objectID);
//hrows.Add(newRow);
popupContents.Add(new DynamicPopupContent(kvpMapMember.Key, objectID, _featureClassName, this));
}
}
catch (Exception)
{
}
return popupContents;
}
示例6: ValidateCategoryPath
/// <summary>
/// Validates the category path.
/// Should allow categories to match in same order.
/// Can only allow some missings segments
/// </summary>
/// <param name="outline">The outline containing ids and semantic url mappings.</param>
/// <param name="requestedPath">The requested path. Containing category codes code1/code2/.../codeN</param>
/// <returns></returns>
protected virtual bool ValidateCategoryPath(Dictionary<string, string> outline, string requestedPath)
{
var prevCatIndex = -1;
var outlineIds = outline.Keys.ToList();
foreach (
var segment in requestedPath.Split(this.Separator.ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
{
var category =
outline.FirstOrDefault(
x =>
x.Key.Equals(segment, StringComparison.InvariantCultureIgnoreCase)
|| x.Value.Equals(segment, StringComparison.InvariantCultureIgnoreCase));
//Category must exist
if (category.Equals(default(KeyValuePair<string, string>)))
{
return false;
}
var currentCatIndex = outlineIds.IndexOf(category.Key);
//Segments order must match outline order
if (prevCatIndex > 0 && prevCatIndex > currentCatIndex)
{
return false;
}
prevCatIndex = currentCatIndex;
}
return true;
}
示例7: GenerateReportData
private static HashSet<FinancialReport> GenerateReportData(
List<string> vendors,
Dictionary<string, decimal> vendorsIncomes,
Dictionary<string, decimal> vendorsExpenses,
Dictionary<string, decimal> vendorsTaxes)
{
var vendorsReport = new HashSet<FinancialReport>();
foreach (var vendor in vendors)
{
var incomes = vendorsIncomes.FirstOrDefault(v => v.Key == vendor);
var expenses = vendorsExpenses.FirstOrDefault(v => v.Key == vendor);
var taxes = vendorsTaxes.FirstOrDefault(v => v.Key == vendor);
var vendorReport = new FinancialReport
{
Vendor = vendor,
Incomes = incomes.Value,
Expenses = expenses.Value,
TotalTaxes = taxes.Value
};
vendorsReport.Add(vendorReport);
}
return vendorsReport;
}
示例8: Main
static void Main()
{
var inputList = new List<int>() { 2, 2, 3, 3, 2, 3, 4, 3, 3 };
var occurs = new Dictionary<int, int>();
for (int i = 0; i < inputList.Count; i++)
{
if (!occurs.ContainsKey(inputList[i]))
{
occurs.Add(inputList[i], 1);
}
else
{
occurs[inputList[i]]++;
}
}
int maxOccurs = 0;
foreach (KeyValuePair<int, int> pair in occurs)
{
if (pair.Value > maxOccurs)
{
maxOccurs = pair.Value;
}
}
var myValue = occurs.FirstOrDefault(x => x.Value == maxOccurs).Key;
Console.WriteLine("Result: ");
Console.WriteLine(myValue);
}
示例9: PostByMonthName
public ActionResult PostByMonthName(short year, string month, short day, string title)
{
month = month.ToLower();
var months = new Dictionary<int, string>();
months.Add(1, "jan");
months.Add(2, "feb");
months.Add(3, "mar");
months.Add(4, "apr");
months.Add(5, "may");
months.Add(6, "jun");
months.Add(7, "jul");
months.Add(8, "aug");
months.Add(9, "sep");
months.Add(10, "oct");
months.Add(11, "nov");
months.Add(12, "dec");
var nowMonth = from m in months
where m.Value == "January"
select m;
foreach(var entry in nowMonth) {
Console.WriteLine(entry.Value);
}
Func<int, int> square = x => x * x;
var squaredValue = square(25);
var currentMonth = months.FirstOrDefault(m => month.Contains(m.Value));
if (currentMonth.Value != null)
{
var currentDate = new DateTime(year, currentMonth.Key, day);
var post = title == null ?
BlogPosts.FirstOrDefault(p => p.PublishDate == currentDate) :
BlogPosts.FirstOrDefault(p => p.PublishDate == currentDate && p.Title == title);
return View("Post", post);
}
return View("Post");
}
示例10: StateActionMapping
public void StateActionMapping(double[, ,] R, List<string> _States, int dim, int FinalStateIndex)
{
Dictionary<int, string> dctStates = new Dictionary<int, string>();
List<string> nextStepStates = new List<string>();
List<int> nextStepIndeces = new List<int>();
for (int i = 0; i < _States.Count; i++)
dctStates.Add(i, _States[i]);
for (int i = 0; i < dctStates.Count; i++)
{
GetNextStates(nextStepStates, dctStates[i], false);
for (int j = 0; j < nextStepStates.Count; j++)
{
nextStepIndeces.Add(dctStates.FirstOrDefault(state => state.Value == nextStepStates[j]).Key);
}
for (int j = 0; j < nextStepIndeces.Count; j++)
{
R[i, j, 1] = nextStepIndeces[j];
R[i, j, 0] = nextStepIndeces[j] == FinalStateIndex ? 100 : 0;
}
nextStepStates.Clear();
nextStepIndeces.Clear();
}
R[FinalStateIndex, 2, 1] = FinalStateIndex;
R[FinalStateIndex, 2, 0] = 100;
}
示例11: GetThrottle
private static double GetThrottle(double rpm_factor, double throttle)
{
var map1 = new Dictionary<double, double>();
var map2 = new Dictionary<double, double>();
var prevmap = ThrottleMap.FirstOrDefault();
double duty_y = 0;
foreach(var d in ThrottleMap)
{
if (d.Key >= rpm_factor && prevmap.Key <= rpm_factor)
{
duty_y = (rpm_factor - prevmap.Key) / (d.Key - prevmap.Key);
map1 = d.Value;
map2 = prevmap.Value;
break;
}
prevmap = d;
}
// Interpolate curves
var prevthrottle = map1.FirstOrDefault();
var percents1 = new double[2] {0, 0};
var percents2 = new double[2] {0, 0};
double duty_x = 0;
foreach(var d in map1)
{
if (prevthrottle.Key <= throttle && throttle <= d.Key && prevthrottle.Key != 0)
{
duty_x = (throttle - prevthrottle.Key)/(d.Key - prevthrottle.Key);
percents1[0] = prevthrottle.Value;
percents1[1] = d.Value;
break;
}
prevthrottle = d;
}
foreach(var d in map2)
{
if (prevthrottle.Key <= throttle && throttle <= d.Key && prevthrottle.Key != 0)
{
percents2[0] = prevthrottle.Value;
percents2[1] = d.Value;
break;
}
prevthrottle = d;
}
// The magic happens here
double factor = duty_y*(duty_x*percents1[1] + (1 - duty_x)*percents1[0])
+ (1 - duty_y)*(duty_x*percents2[1] + (1 - duty_x)*percents2[0]);
if (throttle*factor >= 2)
factor = throttle;
if(factor<=0)
factor = throttle;
if (double.IsNaN(factor) || double.IsInfinity(factor))
factor = throttle;
Console.WriteLine(String.Format("{0:0.0000} -> {1:0.0000}", throttle, factor));
throttle = factor;
return throttle;
}
示例12: Subscribe
public bool Subscribe(NguiBaseBinding binding, NotifyPropertyChanged handler) {
var context = binding.GetContext(Text);
if (context == null) {
return false;
}
var properties = new Dictionary<Type, Property>() {
{typeof(bool), context.FindProperty<bool>(Text, binding)},
{typeof(int), context.FindProperty<int>(Text, binding)},
{typeof(float), context.FindProperty<float>(Text, binding)},
{typeof(double), context.FindProperty<double>(Text, binding)}
};
var pair = properties.FirstOrDefault(x => x.Value != null);
if (pair.Equals(default(KeyValuePair<Type, Property>))) {
return false;
}
type = pair.Key;
property = pair.Value;
//Предотвращеие двойной подписи
property.OnChange -= handler;
property.OnChange += handler;
return true;
}
示例13: Main
static void Main(string[] args)
{
Dictionary<string, int> data = new Dictionary<string, int>();
string input;
Console.Write("Enter count of numbers:");
int count = int.Parse(Console.ReadLine());
for (int index = 0; index < count; index++)
{
Console.Write("Element = ");
input = Console.ReadLine();
if (!data.ContainsKey(input))
{
data.Add(input, 1);
}
else
{
data[input] = data[input] + 1;
}
}
int majorant = count / 2 + 1;
if (data.Values.Contains(majorant))
{
Console.WriteLine("Majorant is " + data.FirstOrDefault(x => x.Value == majorant).Key);
}
else
{
Console.WriteLine("No majorant founded!");
}
}
示例14: BinaryToHexadecimal
static string BinaryToHexadecimal(string bin)
{
string hex = "";
Dictionary<string, string> matrixBinHex = new Dictionary<string, string>{
{"0", "0000"},
{"1", "0001"},
{"2", "0010"},
{"3", "0011"},
{"4", "0100"},
{"5", "0101"},
{"6", "0110"},
{"7", "0111"},
{"8", "1000"},
{"9", "1001"},
{"A", "1010"},
{"B", "1011"},
{"C", "1100"},
{"D", "1101"},
{"E", "1110"},
{"F", "1111"},
};
// 0111 1001
for (int i = 0; i < bin.Length; i += 4)
{
string temp = "";
string digit = bin.Substring(i, 4);
temp = matrixBinHex.FirstOrDefault(x => x.Value.Contains(digit)).Key;
hex += temp;
}
return hex;
}
示例15: Start
void Start()
{
if (gManager == this)
{
isPaused = false;
iManager = new InputManager(0.1f, 0.2f); // It could be helpful, I guess.
tagged_objects = GameObject.FindGameObjectsWithTag("Scene_Object");
scene_objects = new ISceneObject[tagged_objects.Length];
iManager.Initialize();
// Initialize the list of scene objects, all of which have ONE ISceneObject component.
for (int i = 0; i < tagged_objects.Length; i++)
{
scene_objects[i] = tagged_objects[i].GetComponent<ISceneObject>(); // Grab all of those scene objects!
}
// Initialize all scene objects.
for (int j = 0; j < scene_objects.Length; j++)
{
scene_objects[j].Initialize();
}
levelDictionary = new Dictionary<GameState, string>() { { GameState.TLEVELONE, "GMLevel1" },
{ GameState.TLEVELTWO, "GMLevel2" },
{GameState.LEVELONE, "Level1" },
{GameState.LEVELTWO, "Level2" },
{ GameState.LEVELTHREE, "Level3"},
{GameState.LEVELFOUR, "Level4" } };
// This will break on regular levels, handle regular levels separately.
GameManager.gState = levelDictionary.FirstOrDefault(x => x.Value == _testLevelPrefix + SceneManager.GetActiveScene().name).Key;
if(GameManager.m_Camera != null)
{
transform.Find("PauseScreen").gameObject.GetComponent<Canvas>().worldCamera = GameManager.m_Camera;
}
}
}