本文整理汇总了C#中Dictionary.OrderByDescending方法的典型用法代码示例。如果您正苦于以下问题:C# Dictionary.OrderByDescending方法的具体用法?C# Dictionary.OrderByDescending怎么用?C# Dictionary.OrderByDescending使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Dictionary
的用法示例。
在下文中一共展示了Dictionary.OrderByDescending方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Correct
public static string Correct(string word)
{
if (string.IsNullOrEmpty(word))
return word;
word = word.ToLower();
if (_dictionary.ContainsKey(word))
return word;
List<String> list = Edits(word);
Dictionary<string, int> candidates = new Dictionary<string, int>();
FindCandidates(list, ref candidates);
if (candidates.Count > 0)
return candidates.OrderByDescending(x => x.Value).First().Key;
foreach (string item in list)
{
FindCandidates(Edits(item), ref candidates);
}
return (candidates.Count > 0) ? candidates.OrderByDescending(x => x.Value).First().Key : word;
}
示例2: Correct
public string Correct(string word)
{
if (string.IsNullOrEmpty(word))
return word;
word = word.ToLower();
// known()
if (_dictionary.ContainsKey(word))
return word;
List<String> list = Edits(word);
Dictionary<string, int> candidates = new Dictionary<string, int>();
foreach (string wordVariation in list)
{
if (_dictionary.ContainsKey(wordVariation) && !candidates.ContainsKey(wordVariation))
candidates.Add(wordVariation, _dictionary[wordVariation]);
}
if (candidates.Count > 0)
return candidates.OrderByDescending(x => x.Value).First().Key;
// known_edits2()
foreach (string item in list)
{
foreach (string wordVariation in Edits(item))
{
if (_dictionary.ContainsKey(wordVariation) && !candidates.ContainsKey(wordVariation))
candidates.Add(wordVariation, _dictionary[wordVariation]);
}
}
return (candidates.Count > 0) ? candidates.OrderByDescending(x => x.Value).First().Key : word;
}
示例3: SortCollection
/// <summary>
/// Sort the collection in the proper manner.
/// </summary>
internal static Dictionary<string, ListDictionary> SortCollection(Dictionary<string, ListDictionary> collection, string treeLevel, string sortLevel)
{
switch (sortLevel)
{
case "Alphabet":
return collection
.OrderBy(kvp => kvp.Key)
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
case "Effort":
return collection
.OrderByDescending(kvp => kvp.Value["effort"])
.ThenBy(kvp => kvp.Key) // Sort alphabetically if there is a tie.
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
case "Priority":
return collection
.OrderByDescending(kvp => kvp.Value["priority"])
.ThenBy(kvp => kvp.Key) // Sort alphabetically if there is a tie.
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
case "Product":
var missingTeamString = SimpleWorkItem.GetMissingString("Team");
var missingTeamCollection = collection.Where(kvp => kvp.Key == missingTeamString); // Reference the 'NO TEAM' grouping.
return collection
.Where(kvp => kvp.Key != missingTeamString) // Exclude 'NO TEAM' from sorting.
.OrderBy(kvp => kvp.Key != "Atlas")
.ThenBy(kvp => kvp.Key != "Anubis")
.ThenBy(kvp => kvp.Key != "Proteus")
.ThenBy(kvp => kvp.Key != "Shiva")
.ThenBy(kvp => kvp.Key != "Janus")
.ThenBy(kvp => kvp.Key != "Phoenix")
.ThenBy(kvp => kvp.Key != "Brahma")
.ThenBy(kvp => kvp.Key != "Loki")
.ThenBy(kvp => kvp.Key != "Heimdall")
.ThenBy(kvp => kvp.Key != "Vulcan")
.ThenBy(kvp => kvp.Key != "Athena")
.ThenBy(kvp => kvp.Key != "Ra")
.ThenBy(kvp => kvp.Key) // Any unmentioned teams above will be sorted alphabetically.
.Concat(missingTeamCollection) // Attach 'NO TEAM' back on.
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
case "Date":
const string futureString = "Future";
var missingString = SimpleWorkItem.GetMissingString(treeLevel);
var futureCollection = collection.Where(kvp => kvp.Key == futureString); // Reference the Future grouping.
var missingCollection = collection.Where(kvp => kvp.Key == missingString); // Reference the missing grouping.
return collection
.Where(kvp => kvp.Key != futureString && kvp.Key != missingString) // Exclude Future and missing from sorting.
.OrderBy(kvp => kvp.Key.Split('\\').ElementAtOrDefault(0, "Z")) // Sort by Year, using "Z" to place it last if it's missing.
.ThenBy(kvp => kvp.Key.Split('\\').ElementAtOrDefault(1, "Z")) // Sort by Quarter, using "Z" to place it last if it's missing.
.ThenBy(kvp => kvp.Key.Split('\\').ElementAtOrDefault(2, "Z")) // Sort by Sprint, using "Z" to place it last if it's missing.
.Concat(futureCollection) // Attach Future back on.
.Concat(missingCollection) // Attach missing back on.
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
default:
throw new Exception("Sorting type: " + sortLevel + ", is not supported.");
}
}
示例4: WriteStats
internal static void WriteStats(List<ChangeList> allChangelists)
{
var commentForTesterIsNull = 0;
var commentForTesterIsEmpty = 0;
var commentForTesterIsNc = 0;
var commentForTesterIsNullByAuthor = new Dictionary<string, int>();
var commentForTesterIsEmptyByAuthor = new Dictionary<string, int>();
var commentForTesterIsNcByAuthor = new Dictionary<string, int>();
foreach (var changelist in allChangelists)
{
var description = changelist.ParsedDescription;
if (description.CommentForTestersTrimmed == null)
{
commentForTesterIsNull++;
if (commentForTesterIsNullByAuthor.ContainsKey(changelist.Author))
commentForTesterIsNullByAuthor[changelist.Author]++;
else
commentForTesterIsNullByAuthor[changelist.Author] = 1;
}
else if (description.CommentForTestersTrimmed == "")
{
commentForTesterIsEmpty++;
if (commentForTesterIsEmptyByAuthor.ContainsKey(changelist.Author))
commentForTesterIsEmptyByAuthor[changelist.Author]++;
else
commentForTesterIsEmptyByAuthor[changelist.Author] = 1;
}
else if (string.Equals(description.CommentForTestersTrimmed, "nc", StringComparison.OrdinalIgnoreCase))
{
commentForTesterIsNc++;
if (commentForTesterIsNcByAuthor.ContainsKey(changelist.Author))
commentForTesterIsNcByAuthor[changelist.Author]++;
else
commentForTesterIsNcByAuthor[changelist.Author] = 1;
}
}
Console.WriteLine("Comment for tester is null: {0}, authors: {1}, top: {2}-{3}", commentForTesterIsNull, commentForTesterIsNullByAuthor.Count, commentForTesterIsNullByAuthor.OrderByDescending(a => a.Value).First().Key, commentForTesterIsNullByAuthor.OrderByDescending(a => a.Value).First().Value);
Console.WriteLine("Comment for tester is empty: {0}, authors: {1}, top: {2}-{3}", commentForTesterIsEmpty, commentForTesterIsEmptyByAuthor.Count, commentForTesterIsEmptyByAuthor.OrderByDescending(a => a.Value).First().Key, commentForTesterIsEmptyByAuthor.OrderByDescending(a => a.Value).First().Value);
Console.WriteLine("Comment for tester is nc: {0}, authors: {1}, top: {2}-{3}", commentForTesterIsNc, commentForTesterIsNcByAuthor.Count, commentForTesterIsNcByAuthor.OrderByDescending(a => a.Value).First().Key, commentForTesterIsNcByAuthor.OrderByDescending(a => a.Value).First().Value);
Console.WriteLine("Comment for tester is null");
foreach (var author in commentForTesterIsNullByAuthor.OrderByDescending(a => a.Value))
{
Console.WriteLine("{0}: {1}", author.Key, author.Value);
}
Console.WriteLine("Comment for tester is empty");
foreach (var author in commentForTesterIsEmptyByAuthor.OrderByDescending(a => a.Value))
{
Console.WriteLine("{0}: {1}", author.Key, author.Value);
}
Console.WriteLine("Comment for tester is nc");
foreach (var author in commentForTesterIsNcByAuthor.OrderByDescending(a => a.Value))
{
Console.WriteLine("{0}: {1}", author.Key, author.Value);
}
}
示例5: Main
static void Main(string[] args)
{
string[] input = File.ReadAllLines("input.txt");
foreach (string line in input)
{
Reindeers.Add(ParseReindeer(line));
}
Dictionary<Reindeer, int> raceDistancesStar1 = new Dictionary<Reindeer, int>();
raceDistancesStar1 = CalculateRace(2503);
foreach (KeyValuePair<Reindeer, int> raceDistance in raceDistancesStar1.OrderByDescending(d => d.Value))
{
Console.WriteLine($"Reindeer: {raceDistance.Key.Name}, Distance: {raceDistance.Value}");
}
Console.WriteLine($"Day 14 - Star 1, Answer: {raceDistancesStar1.OrderByDescending(rd => rd.Value).First().Key.Name} - {raceDistancesStar1.OrderByDescending(rd => rd.Value).First().Value} km");
Dictionary<Reindeer, int> extraPoints = new Dictionary<Reindeer, int>();
Dictionary<Reindeer, int> raceDistancesStar2 = new Dictionary<Reindeer, int>();
for (int i = 1; i <= 2503; i++)
{
raceDistancesStar2 = CalculateRace(i);
// Give current leading reindeer(s) bonus point
IEnumerable<KeyValuePair<Reindeer, int>> leadingReindeers = raceDistancesStar2.Where(rd => rd.Value == raceDistancesStar2.Max(d => d.Value));
foreach (KeyValuePair<Reindeer, int> leadingReindeer in leadingReindeers)
{
if (!extraPoints.ContainsKey(leadingReindeer.Key))
{
extraPoints.Add(leadingReindeer.Key, 0);
}
extraPoints[leadingReindeer.Key]++;
}
}
foreach (KeyValuePair<Reindeer, int> raceDistance in raceDistancesStar2.OrderByDescending(d => d.Value))
{
int points = 0;
extraPoints.TryGetValue(raceDistance.Key, out points);
Console.WriteLine($"Reindeer: {raceDistance.Key.Name}, Distance: {raceDistance.Value}, Points: {points}");
}
Console.WriteLine($"Day 14 - Star 2, Answer: {extraPoints.OrderByDescending(rd => rd.Value).First().Key.Name} - {extraPoints.OrderByDescending(rd => rd.Value).First().Value} points");
Console.ReadKey();
}
示例6: Main
static void Main(string[] args)
{
string s = "заданная,по,умолчанию,строка,на,входе,в,которой,производится,поиск,триплетов";
Dictionary<string,int> triplet = new Dictionary<string,int>(); //список триплетов с количеством повторений каждого
Console.Write("Введите строку: ");
s=Console.ReadLine();
int err = Check(ref s); //проверка строки
if (err == 0) //строка соответствует условию, в строке больше одного триплета
{
int i = 3;
string trip = s.Substring(0, 3).ToLower(); //выделение подстроки с приведением к строчным буквам (считаем триплеты «Три» и «три» одинаковыми)
triplet.Add(trip, 1); //первый триплет автоматически попадает в список
while (i < s.Length)
{
if (Char.IsLetter(s[i])) //продолжается ли слово
{
trip = trip.Substring(1) + Char.ToLower(s[i]); //изменение триплета
if (triplet.ContainsKey(trip)) //есть ли уже такой триплет
{
triplet[trip]++; //увеличение количества вхождений для найденного триплета
}
else
{
triplet.Add(trip, 1); //добавление нового триплета
}
i++;
}
else
{
trip = s.Substring(i, 3); // натолкнулись на запятую, создаём триплет, содержащий её и две следующие буквы. Так как из строки удалены слова из двух букв, триплет гарантировано будет
i += 3;
}
}
Console.WriteLine(String.Concat(triplet.OrderByDescending(x => x.Value).FirstOrDefault().Key, " ", triplet.OrderByDescending(x => x.Value).FirstOrDefault().Value.ToString())); //выводим наиболее частый триплет и число его вхождений
}
else if (err == 1) //в строке только три символа или только одно слово из трёх символов
{
Console.WriteLine(String.Concat(s, " 1"));
}
else if (err == 2) //в строке нет триплетов
{
Console.WriteLine("В строке нет ни одного триплета");
}
else //в строке присутствуют отличные от букв и запятой символы
{
Console.WriteLine("Строка не соответствует условию задачи");
}
Console.ReadKey();
}
示例7: Populate
/// <summary>
/// Populate asynchronously.
/// </summary>
/// <param name="done">The callback.</param>
public void Populate(Action<ISeries> done) {
_series.Populate(() => {
_children = _series.Children.Select(x => new Chapter(x) as IChapter).ToArray();
foreach (var source in _children.OfType<Chapter>()) {
if (source.Number != -1) continue;
var differential = new Dictionary<double, int>();
var origin = null as Chapter;
foreach (var candidate in _children.OfType<Chapter>()) {
if (candidate != source && candidate.Number != -1 && candidate.Volume == source.Volume) {
if (origin != null) {
var difference = Math.Round(candidate.Number - origin.Number, 4);
if (differential.ContainsKey(difference)) {
differential[difference]++;
} else {
differential[difference] = 1;
}
}
origin = candidate;
}
}
if (differential.Count == 0) {
source.Number = origin == null ? 0.5 : origin.Number + origin.Number / 2;
} else {
var shift = differential.OrderByDescending(x => x.Value).FirstOrDefault().Key;
source.Number = Math.Round(origin.Number + (shift <= 0 || shift >= 1 ? 1 : shift) / 2, 4);
}
}
done(this);
});
}
示例8: Main
static void Main(string[] args)
{
try
{
string fileSourcePath = "text.txt";
string fileResultPath = "result.txt";
string fileDictionaryPath = "words.txt";
Dictionary<string, int> dictionary = new Dictionary<string, int>();
using (StreamReader reader = new StreamReader(fileDictionaryPath, Encoding.GetEncoding("windows-1251")))
{
while (!reader.EndOfStream)
{
string word = reader.ReadLine();
dictionary.Add(word, 0);
}
}
using (StreamReader reader = new StreamReader(fileSourcePath, Encoding.GetEncoding("windows-1251")))
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
List<string> wordList = new List<string>(dictionary.Keys);
foreach (string word in wordList)
{
string regex = String.Format("\\b{0}\\b", word);
MatchCollection matches = Regex.Matches(line, regex);
dictionary[word] += matches.Count;
}
}
}
using (StreamWriter writer = new StreamWriter(fileResultPath, false, Encoding.GetEncoding("windows-1251")))
{
foreach (var wordCounter in dictionary.OrderByDescending(key => key.Value))
{
writer.Write(wordCounter.Key);
writer.Write("-");
writer.WriteLine(wordCounter.Value);
}
}
}
catch (ArgumentNullException)
{
Console.WriteLine("Path is null");
}
catch (FileNotFoundException)
{
Console.WriteLine("File not found");
}
catch (DirectoryNotFoundException)
{
Console.WriteLine("Directory not found");
}
catch (IOException)
{
Console.WriteLine("IO exception");
}
}
示例9: Classify
/// <summary>
/// Given an input feature, a feature space and its associated labels, and a positive integer 'k',
/// Determines the 'k' nearest neighbor label for the input feature. The 'k' value corresponds
/// to the number of nearest neighbors to use in the voting process.
///
/// <remarks>
/// "When I have this grid of data points, and I provide one additional example row, find the 'k' number
/// of rows that are most similar, count up the number of occurrences of each label for each row (1 to 'k'),
/// and choose the label with the highest occurrence."
/// </remarks>
/// <see href="http://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm" />
/// </summary>
/// <param name="distanceType">The type of equation to use when measuring the distance between each data point</param>
/// <param name="input">The matrix row to input; must have the same number of columns as the feature space</param>
/// <param name="featureSpace">The feature space matrix; everything we know</param>
/// <param name="labels">The results for each feature space row; what we call each collection of data points</param>
/// <param name="k">The number of nearest neighbors to include in the voting; the label with the most occurrences in 'k' neighbors wins</param>
/// <returns></returns>
public static string Classify(DistanceType distanceType, Number[] input, Matrix featureSpace, IList<string> labels, int k)
{
if (labels.Count() != featureSpace.Rows)
{
throw new ArgumentException("The number of labels must match the number of rows of data in the feature space", "labels");
}
var distances = CalculateDistances(distanceType, featureSpace, input);
var nearestNeighbors = distances.OrderByDescending(d => d.Value).Take(k);
var votes = new Dictionary<string, int>(k);
foreach (var label in nearestNeighbors.Select(neighbor => labels[neighbor.Key]))
{
if (votes.ContainsKey(label))
{
votes[label]++;
}
else
{
votes.Add(label, 1);
}
}
var nearest = votes.OrderByDescending(v => v.Value).First().Key;
return nearest;
}
示例10: Main
static void Main()
{
Dictionary<string, Dictionary<string, int>> stats = new Dictionary<string, Dictionary<string, int>>();
string input;
string pattern1 = @"^([A-Za-z]+\s*[A-Za-z]*)\s*\|\s*([A-Za-z]+[\s.'A-Za-z0-9-]*)";
while ((input = Console.ReadLine()) != "report")
{
Match playerData = Regex.Match(input, pattern1);
string name = playerData.Groups[1].Value.Trim();
string country = playerData.Groups[2].Value.Trim();
name = Regex.Replace(name, @"\s+", " ");
country = Regex.Replace(country, @"\s+", " ");
if(!stats.ContainsKey(country))
stats.Add(country, new Dictionary<string, int>());
if (!stats[country].ContainsKey(name))
stats[country].Add(name, 1);
else stats[country][name]++;
}
var sortedOutput = stats.OrderByDescending(x => x.Value.Skip(0).Sum(y => y.Value));
foreach (var country in sortedOutput)
{
Console.WriteLine("{0} ({1} participants): {2} wins",
country.Key, country.Value.Count, country.Value.Skip(0).Sum(x => x.Value));
}
}
示例11: Main
static void Main(string[] args)
{
const string SplitPattern = @"\s*\|\s*";
Regex regex = new Regex(SplitPattern);
var countryData = new Dictionary<string, List<string>>();
string input = Console.ReadLine();
while (input != "report")
{
string[] tokens = regex.Split(input.Trim());
string athlete = Regex.Replace(tokens[0].Trim(), @"\s+", " ");
string country = Regex.Replace(tokens[1].Trim(), @"\s+", " ");
if (!countryData.ContainsKey(country))
{
countryData.Add(country, new List<string>());
}
countryData[country].Add(athlete);
input = Console.ReadLine();
}
var orderedCountryData = countryData
.OrderByDescending(x => x.Value.Count);
foreach (var country in orderedCountryData)
{
Console.WriteLine(
"{0} ({1} participants): {2} wins",
country.Key,
country.Value.Distinct().Count(),
country.Value.Count);
}
}
示例12: Main
static void Main()
{
string text = @"Write a program that reads a string from the console and prints all different letters in the string along with information how many times each letter is found.";
Dictionary<string, int> words = new Dictionary<string, int>();
string[] wordsInText = text.Split(new char[] { '.', ',', ' ', '!', '?', '-', ':', ';' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var word in wordsInText)
{
if (words.ContainsKey(word))
{
words[word]++;
}
else
{
words.Add(word, 1);
}
}
var sortedWords = words.OrderByDescending(w => w.Value);
foreach (var word in sortedWords)
{
Console.WriteLine("Word \"{0}\" is found {1} time(s)", word.Key, words[word.Key]);
}
}
示例13: FindMajorant
public static int FindMajorant(List<int> input)
{
int majorantMargin = input.Count / 2 + 1;
Dictionary<int, int> valueCount = new Dictionary<int, int>();
for (int i = 0; i < input.Count; i++)
{
if (!valueCount.ContainsKey(input[i]))
{
valueCount[input[i]] = 1;
}
else
{
valueCount[input[i]]++;
}
if (valueCount[input[i]] > majorantMargin)
{
return input[i];
}
}
//handle case when there is no clear winner
int majorant = valueCount.OrderByDescending(x => x.Value).Select(x => x.Key).First();
return majorant;
}
示例14: Main
static void Main()
{
Console.WriteLine("Enter some text with repeated words: ");
string text = Console.ReadLine();
string regex = @"\b\w+\b";
Dictionary<string, int> dictionary = new Dictionary<string, int>();
MatchCollection words = Regex.Matches(text, regex);
foreach (Match word in words)
{
if (dictionary.ContainsKey(word.ToString()))
{
dictionary[word.ToString()] += 1;
}
else
{
dictionary.Add(word.ToString(), 1);
}
}
foreach (var word in dictionary.OrderByDescending(m => m.Value))
{
Console.WriteLine("{0} - {1}", word.Key, word.Value);
}
}
示例15: Main
static void Main()
{
StreamReader wordsReader = new StreamReader("../../words.txt");
StreamReader textReader = new StreamReader("../../text.txt");
StreamWriter resultWriter = new StreamWriter("../../result.txt");
using (wordsReader)
{
using (textReader)
{
using (resultWriter)
{
List<string> words = new List<string>();
string line = wordsReader.ReadLine();
while (line != null)
{
words.Add(line);
line = wordsReader.ReadLine();
}
List<int> wordsCount = new List<int>();
List<string> text = new List<string>();
line = textReader.ReadLine();
while (line != null)
{
text.Add(line);
line = textReader.ReadLine();
}
for (int i = 0; i < words.Count; i++)
{
wordsCount.Add(0);
for (int j = 0; j < text.Count; j++)
{
if (text[j].ToLower().Contains(words[i].ToLower()))
{
wordsCount[i]++;
}
}
}
Dictionary<string, int> dict = new Dictionary<string, int>();
for (int i = 0; i < words.Count; i++)
{
dict[words[i]] = wordsCount[i];
}
var ordered = dict.OrderByDescending(x => x.Value);
foreach (var item in ordered)
{
resultWriter.WriteLine("{0} - {1}", item.Key, item.Value);
}
}
}
}
}