本文整理汇总了C#中Dictionary.Min方法的典型用法代码示例。如果您正苦于以下问题:C# Dictionary.Min方法的具体用法?C# Dictionary.Min怎么用?C# Dictionary.Min使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Dictionary
的用法示例。
在下文中一共展示了Dictionary.Min方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
public static void Main()
{
n = int.Parse(Console.ReadLine());
objects = new int[n];
arr = new int[n];
used = new bool[n];
values = new Dictionary<int, int>();
for (int i = 0; i < n; i++)
{
objects[i] = int.Parse(Console.ReadLine());
}
GenerateVariationsNoRepetitions(0);
var minValues = values.Where(v => v.Value == values.Min(x => x.Value));
if (minValues.Count() == 1)
{
Console.WriteLine(minValues.FirstOrDefault().Key);
}
else
{
Console.WriteLine(minValues.OrderBy(x => x.Key).FirstOrDefault().Key);
}
}
示例2: Down
public int Down(string tableName, string primaryColumn, Int64 primaryValue, string orderColumn, Int64 orderNumber)
{
var data = new Dictionary<string, Int64>();
using (DataCommand cmd = DataCommandManager.GetDataCommand("CommonDown"))
{
cmd.CommandText = string.Format(cmd.CommandText, tableName, primaryColumn, primaryValue, orderColumn,orderNumber);
using (IDataReader dr = cmd.ExecuteDataReader())
{
while (dr.Read())
{
if (!Convert.IsDBNull(dr[primaryColumn]) && !Convert.IsDBNull(dr[orderColumn]))
{
data.Add(dr[primaryColumn].ToString(), Convert.ToInt64(dr[orderColumn]));
}
}
}
if (data.Count == 1)
{
return 2;
}
else
{
string sql = "update {0} set {1}={2} where {3}={4}";
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string, long> keyValuePair in data)
{
if (keyValuePair.Key == primaryValue.ToString())
{
sb.Append(
string.Format(
sql,
tableName,
orderColumn,
data.Min(s => s.Value),
primaryColumn,
primaryValue) + ";");
}
else
{
sb.Append(
string.Format(
sql,
tableName,
orderColumn,
data.Max(s => s.Value),
primaryColumn,
keyValuePair.Key) + ";");
}
}
cmd.CommandText = sb.ToString();
return cmd.ExecuteNonQuery();
}
}
}
示例3: SetChart
public static void SetChart(Dictionary<string, int> rawValues, Chart chart)
{
int fmin = 0;
int fmax = 1;
if (rawValues.Count > 0)
{
fmax = rawValues.Max(x => x.Value);
fmin = rawValues.Min(x => x.Value);
}
//series init
chart.Series.Clear();
// chart.Tag = values;
var s = new Series();
s.ChartType = SeriesChartType.Bar;
foreach (var kvp in rawValues)
{
s.Points.AddXY(kvp.Key, kvp.Value);
var dpc = s.Points[s.Points.Count - 1];
dpc.Color = ColorExtras.GetRedGreenBlendedColour(kvp.Value, 0, fmax);
dpc.ToolTip = kvp.Key + ":" + kvp.Value;
}
s.YAxisType = AxisType.Primary;
s.XAxisType = AxisType.Secondary;
s.IsVisibleInLegend = false;
chart.Series.Add(s);
//chartarea init
chart.ChartAreas.Clear();
var ca = new ChartArea();
// ca.CursorX.IsUserEnabled = true;
// ca.CursorX.IsUserSelectionEnabled = true;
ca.AxisX2.ScrollBar.IsPositionedInside = false;
ca.AxisX2.ScaleView.Size = zoomMax;
ca.AxisX2.ScaleView.Position=rawValues.Count-ca.AxisX2.ScaleView.Size;
ca.AxisX2.Interval = 1;
ca.AxisY.Interval = MathExtras.Ceiling((Math.Abs(fmax) - Math.Abs(fmin)) / 8);
if (ca.AxisY.Interval<1)
ca.AxisY.Interval = 1;
ca.AxisY.Minimum = fmin;
ca.AxisY.Maximum = fmax;
if (Math.Abs(ca.AxisY.Minimum - ca.AxisY.Maximum) < 1)
ca.AxisY.Minimum--;
s.Sort(PointSortOrder.Ascending);
chart.ChartAreas.Add(ca);
}
示例4: Save
public void Save(Dictionary<string, List<News>> news)
{
decimal min = news.Min(n => n.Value.Min(m => m.RawScore));
decimal max = news.Max(n => n.Value.Max(m => m.RawScore));
using (var dbContext = new DistrictsInTownModelContainer())
{
foreach (var district in news)
AddArticlesToDB(dbContext, district, min, max);
try
{
dbContext.SaveChanges();
}
catch (Exception error)
{
Console.WriteLine(error.StackTrace);
}
Console.WriteLine("Total results: {0}", news.Sum(n => n.Value.Count));
}
}
示例5: compute
internal static Dictionary<DateTime, double> compute(Dictionary<DateTime, double> prices, int assetid)
{
bool accessbd = false;
Dictionary<DateTime, double> returns = new Dictionary<DateTime, double>();
DateTime first = prices.Min(t=>t.Key);
DateTime before;
double price = 1;
foreach (KeyValuePair<DateTime, double> kvp in prices)
{
if(kvp.Key != first){
before = kvp.Key.AddDays(-1);
while (!prices.ContainsKey(before) && before >= first) before = before.AddDays(-1);
if (!prices.ContainsKey(before) && before < first)
{
while (1 == 1)
{
try
{
price = AccessBD.Access.get_Price_Eur(assetid, before);
accessbd = true;
break;
}
catch (ArgumentException)
{
before = before.AddDays(-1);
}
}
}
if (accessbd == false)
{
price = prices[before];
}
returns[kvp.Key] = Math.Log(prices[kvp.Key] / price);
}
}
return returns;
}
示例6: Fold
internal void Fold(Dictionary<Int32,FoldRegion> regions)
{
if (regions.Count == 0)
return;
var start = regions.Min(rv => rv.Key);
var end = regions.Max(rv => rv.Value.EndLine);
var lc = @ref.Send(Sci.SCI_GETLINECOUNT);
for (var i = start; i < end + 2; i++)
{
FoldRegion reg;
if (regions.TryGetValue(i, out reg))
{
//System.Diagnostics.Debug.WriteLine("sl=" + i + ";el=" + reg.EndLine + ";level=" + reg.Level);
ProcessRegion(ref i, 0, regions, reg);
i--;
}
else if (i < lc)
@ref.Send(Sci.SCI_SETFOLDLEVEL, i, 0 | Sci.SC_FOLDLEVELBASE);
}
}
示例7: GetUnassignedSessionWithFewestAvailableOptions
internal static Session GetUnassignedSessionWithFewestAvailableOptions(this IEnumerable<Assignment> assignments, IEnumerable<Session> sessions, SessionAvailabilityCollection sessionMatrix)
{
Session result = null;
var assignedSessionIds = assignments.Where(a => a.SessionId != null).Select(a => a.SessionId);
var sessionDictionary = new Dictionary<int, int>();
foreach (var session in sessions.Where(s => !assignedSessionIds.Contains(s.Id)))
{
sessionDictionary.Add(session.Id, sessionMatrix.GetAvailableAssignmentCount(session.Id));
}
if (sessionDictionary.Count() > 0)
{
var min = sessionDictionary.Min(s => s.Value);
var keys = sessionDictionary.Where(sd => sd.Value == min).Select(a => a.Key);
result = sessions.Where(a => keys.Contains(a.Id))
.OrderByDescending(b => b.GetDependentDepth(sessions))
.ThenByDescending(c => c.GetDependentCount(sessions))
.FirstOrDefault();
}
return result;
}
示例8: Runner
//.........这里部分代码省略.........
//If time is exceeded, run it now
if (start <= DateTime.UtcNow)
{
var jobsToRun = new List<Server.Runner.IRunnerData>();
//TODO: Cache this to avoid frequent lookups
foreach(var id in Program.DataConnection.GetBackupIDsForTags(sc.Tags).Distinct().Select(x => x.ToString()))
{
//See if it is already queued
var tmplst = from n in m_worker.CurrentTasks
where n.Operation == Duplicati.Server.Serialization.DuplicatiOperation.Backup
select n.Backup;
var tastTemp = m_worker.CurrentTask;
if (tastTemp != null && tastTemp.Operation == Duplicati.Server.Serialization.DuplicatiOperation.Backup)
tmplst.Union(new [] { tastTemp.Backup });
//If it is not already in queue, put it there
if (!tmplst.Any(x => x.ID == id))
{
var entry = Program.DataConnection.GetBackup(id);
if (entry != null)
jobsToRun.Add(Server.Runner.CreateTask(Duplicati.Server.Serialization.DuplicatiOperation.Backup, entry));
}
}
//Caluclate next time, by adding the interval to the start until we have
// passed the current date and time
//TODO: Make this more efficient
int i = 50000;
while (start <= DateTime.UtcNow && i-- > 0)
try
{
start = GetNextValidTime(start, start.AddSeconds(1), sc.Repeat, sc.AllowedDays);
}
catch(Exception ex)
{
Program.DataConnection.LogError(sc.ID.ToString(), "Scheduler failed to find next date", ex);
continue;
}
Server.Runner.IRunnerData lastJob = jobsToRun.LastOrDefault();
if (lastJob != null && lastJob != null)
lock(m_lock)
m_updateTasks[lastJob] = new Tuple<ISchedule, DateTime, DateTime>(sc, start, DateTime.UtcNow);
foreach(var job in jobsToRun)
m_worker.AddTask(job);
if (start < DateTime.UtcNow)
{
//TODO: Report this somehow
continue;
}
}
scheduled[sc.ID] = start;
}
}
var existing = lst.ToDictionary(x => x.ID);
Server.Serialization.Interface.ISchedule sc_tmp = null;
//Sort them, lock as we assign the m_schedule variable
lock(m_lock)
m_schedule = (from n in scheduled
where existing.TryGetValue(n.Key, out sc_tmp)
orderby n.Value
select existing[n.Key]).ToArray();
// Remove unused entries
foreach(var c in (from n in scheduled where !existing.ContainsKey(n.Key) select n.Key).ToArray())
scheduled.Remove(c);
//Raise event if needed
if (NewSchedule != null)
NewSchedule(this, null);
int waittime = 0;
//Figure out a sensible amount of time to sleep the thread
if (scheduled.Count > 0)
{
//When is the next run scheduled?
TimeSpan nextrun = scheduled.Min((x) => x.Value) - DateTime.UtcNow;
if (nextrun.TotalMilliseconds < 0)
continue;
//Don't sleep for more than 5 minutes
waittime = (int)Math.Min(nextrun.TotalMilliseconds, 60 * 1000 * 5);
}
else
{
//No tasks, check back later
waittime = 60 * 1000;
}
//Waiting on the event, enables a wakeup call from termination
// never use waittime = 0
m_event.WaitOne(Math.Max(100, waittime), false);
}
}
示例9: readChart
//.........这里部分代码省略.........
previoustime += (previousbps == 0 ? 0 : (theBpmListMesured.First().Key - previousmesure)/previousbps);
previousbps = theBpmList.Last().Value/(double)60.0;
previousmesure = theBpmListMesured.First().Key;
theBpmListMesured.Remove(theBpmListMesured.First().Key);
}
var thedisplayBPM = "";
if(listLine.FirstOrDefault(c => c.Contains("DISPLAYBPM")) != null){
try{
string[] thes = listLine.FirstOrDefault(c => c.Contains("DISPLAYBPM")).Split(':');
if(thes.Count() > 2){
thedisplayBPM = System.Convert.ToDouble(thes[1].Replace(";", "")).ToString("0") + " -> " + System.Convert.ToDouble(thes[2].Replace(";", "")).ToString("0");
}else{
thedisplayBPM = System.Convert.ToDouble(thes[1].Replace(";", "")).ToString("0");
}
}catch{ //Special Gravity Blast fix
string[] thes = listLine.FirstOrDefault(c => c.Contains("DISPLAYBPM")).Split(':');
var theindex = 0;
for(int o=0; o<thes.Count(); o++){
if(thes[o].Contains("DISPLAYBPM")){
theindex = o + 1;
}
}
if((thes.Count() - theindex - 1) > 2){
thedisplayBPM = System.Convert.ToDouble(thes[theindex].Replace(";", "")).ToString("0") + " -> " + System.Convert.ToDouble(thes[theindex+1].Replace(";", "")).ToString("0");
}else{
thedisplayBPM = System.Convert.ToDouble(thes[theindex].Replace(";", "")).ToString("0");
}
}
}else{
var themin = theBpmList.Min(c => c.Value);
var themax = theBpmList.Max(c => c.Value);
if(themin == themax){
thedisplayBPM = themax.ToString("0");
}else{
thedisplayBPM = themin.ToString("0") + " -> " + themax.ToString("0");
}
}
//debug
/*foreach(var el in theStopList){
Debug.Log(el.Key);
}*/
//For all difficulties
foreach(int index in indexNotes){
var theNewsong = new Song();
//easy variable getted
theNewsong.title = title;
theNewsong.subtitle = subtitle;
theNewsong.artist = artist;
theNewsong.banner = banner;
theNewsong.offset = offset;
theNewsong.samplestart = samplestart;
theNewsong.samplelenght = samplelenght;
theNewsong.bpms = theBpmList;
theNewsong.stops = theStopList;
theNewsong.mesureBPMS = theBpmMesureList;
theNewsong.mesureSTOPS = theStopMesureList;
theNewsong.bpmToDisplay = thedisplayBPM;
/*if(files.FirstOrDefault(c => c.Contains(".ogg")) == null){
示例10: GetOrderDetails
// Method to return purchase order details
public Dictionary<string, object> GetOrderDetails()
{
// Insert regular and purchase price into cart for each item
foreach (Dictionary<string, object> orderItem in this.OrderItems)
{
// Get records related to the item
IEnumerable<DataRow> items =
DBHelper.GetTable("Items").Table.AsEnumerable().Where(
item => item["UPC"].ToString().Equals(orderItem["UPC"].ToString()));
IEnumerable<DataRow> promotions =
DBHelper.GetTable("Promotions").Table.AsEnumerable().Where(
promotion => promotion["UPC"].ToString().Equals(orderItem["UPC"].ToString()) &&
((DateTime)promotion["PromotionFrom"]).CompareTo(DateTime.Now) <= 0 &&
((DateTime)promotion["PromotionTo"]).CompareTo(DateTime.Now) >= 0);
// Get name of the item
orderItem["ItemName"] = items.First()["ItemName"].ToString();
// Set regular price and purchase price
double? regularPrice = null;
double? memberPrice = null;
double? promotionalPrice = null;
// Regular price depends on if the customer is member
if (this.OrderDetails["UserId"] != null)
{
regularPrice = double.Parse(items.First()["TenDaysPrice"].ToString());
}
else
{
regularPrice = double.Parse(items.First()["RegularPrice"].ToString());
}
// Get member price
if (string.IsNullOrEmpty(items.First()["MemberPrice"].ToString()))
{
memberPrice = null;
}
else
{
memberPrice = double.Parse(items.First()["MemberPrice"].ToString());
}
// Get promotional price
if (promotions.Count() != 0)
{
promotionalPrice = double.Parse(items.First()["PromotionalPrice"].ToString());
}
// Set regular price to item ordered
orderItem["RegularPrice"] = regularPrice;
Dictionary<string, double?> priceDictionary = new Dictionary<string, double?>();
priceDictionary.Add("RegularPrice", regularPrice);
if (this.OrderDetails["UserId"] != null)
{
priceDictionary.Add("MemberPrice", memberPrice);
}
priceDictionary.Add("PromotionalPrice", promotionalPrice);
// Set purchase price
if (this.OrderDetails["UserId"] != null)
{
double? purchasePrice = priceDictionary.Min(pair => pair.Value);
orderItem["PurchasePrice"] = purchasePrice;
}
else
{
double? purchasePrice = priceDictionary.Min(pair => pair.Value);
orderItem["PurchasePrice"] = purchasePrice;
}
// If the cart belongs to member, save the price to database
if (this.OrderDetails["UserId"] != null)
{
Dictionary<string, object> updatedRecord = new Dictionary<string, object>();
updatedRecord.Add("OrderId", orderItem["OrderId"]);
updatedRecord.Add("UPC", orderItem["UPC"]);
updatedRecord.Add("RegularPrice", orderItem["RegularPrice"]);
updatedRecord.Add("PurchasePrice", orderItem["PurchasePrice"]);
DBHelper.Update("OrderItems", updatedRecord);
}
}
return this.OrderDetails;
}
示例11: DictionaryExtensions_Min_ThrowsExceptionIfDictionaryIsEmpty
public void DictionaryExtensions_Min_ThrowsExceptionIfDictionaryIsEmpty()
{
var dictionary = new Dictionary<Int32, String>();
Assert.That(() => dictionary.Min(x => x.Key),
Throws.TypeOf<InvalidOperationException>());
}
示例12: DictionaryExtensions_Min_ReturnsMinValue
public void DictionaryExtensions_Min_ReturnsMinValue()
{
var dictionary = new Dictionary<Int32, String>()
{
{ 4, "A" },
{ 5, "B" },
{ 6, "C" },
{ 99, "D" },
{ 10, "E" },
{ 1, "F" },
{ 12, "G" },
{ 45, "H" },
};
var result = dictionary.Min(x => x.Key);
TheResultingValue(result).ShouldBe(1);
}
示例13: computeNearestNeighbour
private Dictionary<string, double> computeNearestNeighbour(string targetUser)
{
Dictionary<string, double> nearestNeighbourDict = new Dictionary<string, double>();
foreach (var user in userDictionary)
{
if(!user.Key.Equals(targetUser))
{
double similarity = similarityStrategy.computeSimilarity(userDictionary[targetUser].userPreferenceDictionary,
userDictionary[user.Key].userPreferenceDictionary);
int targetPreferenceCount = userDictionary[targetUser].userPreferenceDictionary.Count;
int userPreferenceCount = userDictionary[user.Key].userPreferenceDictionary.Count;
if (similarity > predefinedSimilarity && userPreferenceCount > targetPreferenceCount)
{
if(nearestNeighbourDict.Count < k)
{
nearestNeighbourDict.Add(user.Key, similarity);
}
else
{
// if list is full check for the minimum similarity and remove it,
// to add the new user and update the predefinedSimilarity treshold.
// http://stackoverflow.com/questions/23734686/c-sharp-dictionary-get-the-key-of-the-min-value
var minUser = nearestNeighbourDict.Aggregate((x, y) => x.Value < y.Value ? x : y);
if (similarity > minUser.Value)
{
nearestNeighbourDict.Remove(minUser.Key);
nearestNeighbourDict.Add(user.Key, similarity);
predefinedSimilarity = nearestNeighbourDict.Min(x => x.Value);
}
}
}
}
}
//create a new dictionary with the results sorted by descending.
Dictionary<string, double> resultDictionary = new Dictionary<string, double>();
foreach(var keypair in nearestNeighbourDict.OrderByDescending(x => x.Value))
{
resultDictionary.Add(keypair.Key, keypair.Value);
}
return resultDictionary;
}
示例14: PerformTeachingSerie
private void PerformTeachingSerie(int wantedNoOfNodes, int changesPerPatch, int patchesPerTeachingSerie)
{
// patch --> its error change - lower = better
Dictionary<NetworkPatch, double> patchesEfficiency = new Dictionary<NetworkPatch, double>();
double serieStartError = network_.CalculateTrainingSqrError();
int startNetworkHash = network_.GetHashCode();
while (patchesEfficiency.Count < patchesPerTeachingSerie)
{
#if DEBUG
string graphBeforePatch = network_.PrintNetworkStruct();
#endif
NetworkPatch patch = patchFactory_.CreateAndApplyPatch(changesPerPatch, wantedNoOfNodes);
patchesEfficiency[patch] = network_.CalculateTrainingSqrError() - serieStartError;
#if DEBUG
string graphAfterPatch = network_.PrintNetworkStruct();
#endif
patch.Revert();
#if DEBUG
string graphAfterRevert = network_.PrintNetworkStruct();
double errorAfterNotApplyingPatch = network_.CalculateTrainingSqrError();
if (serieStartError != errorAfterNotApplyingPatch)
{
Logger.Log(this, String.Format(
"REVERT WENT WRONG!\n" +
"<<<<<<<<<<<<GRAPH BEFORE PATCH >>>>>>>>>>\n{0}\n" +
"<<<<<<<<<<<<GRAPH AFTER PATCH >>>>>>>>>>\n{1}\n" +
"<<<<<<<<<<<<GRAPH AFTER REVERT >>>>>>>>>>\n{2}\n",
graphBeforePatch,
graphAfterPatch,
graphAfterRevert),
10);
throw new ApplicationException("revert went wrong");
}
#endif
}
//NOTE: what is interesting double.NaN is lowest possible number AND double.NaN != double.NaN //WTF??
double bestChange = patchesEfficiency.Min(x => double.IsNaN(x.Value) ? double.PositiveInfinity : x.Value);
Logger.Log(this, String.Format("best change {0}", bestChange));
if (bestChange <= 0.0d && //IMPORTANT: for now only
!double.IsInfinity(bestChange) &&
!double.IsNaN(bestChange))
{
Logger.Log(this, "applying patch!");
NetworkPatch bestPatch = patchesEfficiency.First(patch => patch.Value == bestChange).Key;
bestPatch.Apply();
double errorAfterApplyingPatch = network_.CalculateTrainingSqrError();
Logger.Log(this, String.Format("error after appplying patch {0}", errorAfterApplyingPatch));
//#if DEBUG
if (bestChange < -1E-2)
{
PrintGraphVisualization(network_);
}
//#endif
double delta = 1E-4;
if (serieStartError + bestChange - errorAfterApplyingPatch > delta)
throw new ApplicationException("something went rly bad");
}
else
{
Logger.Log(this, "NOT applying patch");
}
}
示例15: GetHeaderColumnPosition
public uint GetHeaderColumnPosition(WorksheetEntry worksheet, Dictionary<string, uint> sectionLines, string columnName)
{
var rowLine = sectionLines.Min(spp => spp.Value) - 1;
var headerSectionLine = _spreadsheetFacade.GetCellsValues(worksheet, rowLine, rowLine, 1, uint.MaxValue).ToList();
return headerSectionLine.Where(h => h.Value.Equals(columnName)).Select(h => h.Column).First();
}