public void TokenFunctionTest(string equalsToken, string plusToken, int collectionSize) { var kvps = new KeyValuePair <string, string> [collectionSize]; Random rand1 = new Random(); for (int i = 0; i < collectionSize; i++) { kvps[i] = new KeyValuePair <string, string>($"key{i}", $"{Guid.NewGuid()}{Guid.NewGuid()}{Guid.NewGuid()}"); } string value1 = kvps[rand1.Next(0, collectionSize - 1)].Value; string value2 = kvps[rand1.Next(0, collectionSize - 1)].Value; string queryString = $"value{equalsToken}{value1}{plusToken}{value2}"; var sw = Stopwatch.StartNew(); var expression = ExpressionBuilder.BuildFunction <KeyValuePair <string, string> >(queryString); kvps.FirstOrDefault(expression).Should().NotBeNull().And .Should().BeAnyOf(kvps.Where(kvp => kvp.Value == value1 || kvp.Value == value2)); kvps.Where(expression).Should().NotBeNullOrEmpty().And .Contain(kvps.Where(kvp => kvp.Value == value1 || kvp.Value == value2)); kvps.Any(expression).Should().BeTrue(); kvps.All(expression).Should().BeFalse(); kvps.Count(expression).Should().Be(kvps.Count(q => q.Value == value1 || q.Value == value2)); sw.Stop(); }
public void IntTest(int collectionSize) { var kvps = new KeyValuePair <string, int> [collectionSize]; Random rand1 = new Random(); for (int i = 0; i < collectionSize; i++) { Random rand2 = new Random(rand1.Next(0, int.MaxValue)); kvps[i] = new KeyValuePair <string, int>($"key{i}", rand2.Next(1, collectionSize)); } int value1 = kvps[rand1.Next(0, collectionSize - 1)].Value; int value2 = kvps[rand1.Next(0, collectionSize - 1)].Value; string queryString = $"value={value1}%2B{value2}"; var sw = Stopwatch.StartNew(); var expression = ExpressionBuilder.BuildFunction <KeyValuePair <string, int> >(queryString); kvps.FirstOrDefault(expression).Should().NotBeNull().And .Should().BeAnyOf(kvps.Where(kvp => kvp.Value == value1 || kvp.Value == value2)); kvps.Where(expression).Should().NotBeNullOrEmpty().And .Contain(kvps.Where(kvp => kvp.Value == value1 || kvp.Value == value2)); kvps.Any(expression).Should().BeTrue(); kvps.All(expression).Should().BeFalse(); kvps.Count(expression).Should().Be(kvps.Count(q => q.Value == value1 || q.Value == value2)); sw.Stop(); }
public void StringTest(int collectionSize) { var kvps = new KeyValuePair <string, string> [collectionSize]; Random rand1 = new Random(); for (int i = 0; i < collectionSize; i++) { kvps[i] = new KeyValuePair <string, string>($"key{i}", Guid.NewGuid().ToString() + Guid.NewGuid() + Guid.NewGuid()); } string value1 = kvps[rand1.Next(0, collectionSize - 1)].Value; string value2 = kvps[rand1.Next(0, collectionSize - 1)].Value; string queryString = $"value={value1}%2B{value2}"; IQueryable <KeyValuePair <string, string> > queryable = kvps.AsQueryable(); var sw = Stopwatch.StartNew(); var expression = ExpressionBuilder.BuildExpression <KeyValuePair <string, string> >(queryString); queryable.FirstOrDefault(expression).Should().NotBeNull().And .Should().BeAnyOf(kvps.Where(kvp => kvp.Value == value1 || kvp.Value == value2)); queryable.Where(expression).Should().NotBeNullOrEmpty().And .Contain(kvps.Where(kvp => kvp.Value == value1 || kvp.Value == value2)); queryable.Any(expression).Should().BeTrue(); queryable.All(expression).Should().BeFalse(); queryable.Count(expression).Should().Be(queryable.Count(q => q.Value == value1 || q.Value == value2)); sw.Stop(); }
public void DateTimeListTest(int collectionSize, int maxSubCollectionSize) { var kvps = new KeyValuePair <string, List <DateTime> > [collectionSize]; int day = 1; int month = 1; int year = 2016; for (int i = 0; i < collectionSize; i++) { string key = $"key{i}"; KeyValuePair <string, List <DateTime> > kvp = new KeyValuePair <string, List <DateTime> >(key, new List <DateTime>()); for (int j = 0; j < maxSubCollectionSize; j++) { kvp.Value.Add(new DateTime(year, month, day++)); if (day > 28) { day = 1; month++; } if (month <= 12) { continue; } month = 1; year++; } kvps[i] = kvp; } Random rand = new Random(); DateTime value1 = kvps[rand.Next(0, collectionSize - 1)].Value[0]; DateTime value2 = kvps[rand.Next(0, collectionSize - 1)].Value[0]; string queryString = $"value={value1}%2B{value2}"; var sw = Stopwatch.StartNew(); var expression = ExpressionBuilder.BuildFunction <KeyValuePair <string, List <DateTime> > >(queryString); kvps.FirstOrDefault(expression).Should().NotBeNull().And .Should().BeAnyOf(kvps.Where(kvp => kvp.Value.Contains(value1) || kvp.Value.Contains(value2))); kvps.Where(expression).Should().NotBeNullOrEmpty().And .Contain(kvps.Where(kvp => kvp.Value.Contains(value1) || kvp.Value.Contains(value2))); kvps.Any(expression).Should().BeTrue(); kvps.All(expression).Should().BeFalse(); kvps.Count(expression).Should().Be(kvps.Count(q => q.Value.Contains(value1) || q.Value.Contains(value2))); sw.Stop(); }
public void DateTimeTest(int collectionSize) { var kvps = new KeyValuePair <string, DateTime> [collectionSize]; int day = 1; int month = 1; int year = 2016; for (int i = 0; i < collectionSize; i++) { kvps[i] = new KeyValuePair <string, DateTime>($"key{i}", new DateTime(year, month, day++)); if (day > 28) { day = 1; month++; } if (month <= 12) { continue; } month = 1; year++; } Random rand = new Random(); DateTime value1 = kvps[rand.Next(0, collectionSize - 1)].Value; DateTime value2 = kvps[rand.Next(0, collectionSize - 1)].Value; string queryString = $"value={value1}%2B{value2}"; IQueryable <KeyValuePair <string, DateTime> > queryable = kvps.AsQueryable(); var sw = Stopwatch.StartNew(); var expression = ExpressionBuilder.BuildExpression <KeyValuePair <string, DateTime> >(queryString); queryable.FirstOrDefault(expression).Should().NotBeNull().And .Should().BeAnyOf(kvps.Where(kvp => kvp.Value == value1 || kvp.Value == value2)); queryable.Where(expression).Should().NotBeNullOrEmpty().And .Contain(kvps.Where(kvp => kvp.Value == value1 || kvp.Value == value2)); queryable.Any(expression).Should().BeTrue(); queryable.All(expression).Should().BeFalse(); queryable.Count(expression).Should().Be(queryable.Count(q => q.Value == value1 || q.Value == value2)); sw.Stop(); }
public void GenerateSuffixSearchTestCases(int count) { var vocabulary = NonsenseGeneration.GetVocabulary(); var words = NonsenseGeneration.GetRandomNeighbourWordGroups(vocabulary, count).ToArray(); var idsAndWords = new KeyValuePair <int, string> [words.Length]; for (int i = 0; i < words.Length; i++) { idsAndWords[i] = new KeyValuePair <int, string>(i, words[i]); } using (var output = File.CreateText(string.Format("SuffixSearchTestCases{0}.txt", count))) { WriteArrayDeclaration(count.ToString(), words, output); foreach (var keyValuePair in idsAndWords) { var word = keyValuePair.Value; foreach (var query in GetAllSubstrings(word)) { string query1 = query; var actual = idsAndWords .Where(idWordPair => idWordPair.Value.Contains(query1)) .Select(idWordPair => idWordPair.Key); string array = string.Join(",", actual.Select(id => id.ToString())); output.WriteLine("[TestCase(\"{0}\", new[] {{{1}}})]", query, array); } } } }
public void CopyTo() { var trie = new Trie <bool> { { "ABC", true }, { "AB", false }, { "ADE", true }, { "ABCDE", false } }; var destinationArray = new KeyValuePair <string, bool> [6]; ((ICollection <KeyValuePair <string, bool> >)trie).CopyTo(destinationArray, 1); var result = destinationArray.Where(i => i.Key != null).OrderBy(i => i.Key).ToArray(); var expected = new[] { new KeyValuePair <string, bool>("AB", false), new KeyValuePair <string, bool>("ABC", true), new KeyValuePair <string, bool>("ABCDE", false), new KeyValuePair <string, bool>("ADE", true) }; Assert.AreEqual(new KeyValuePair <string, bool>(), destinationArray[0]); Assert.AreEqual(new KeyValuePair <string, bool>(), destinationArray[destinationArray.Length - 1]); Assert.IsTrue(expected.SequenceEqual(result)); }
static Int64[] ListeGrenzeAusÜberscnaidung1D( Int64 RegioonAScrankeMin, Int64 RegioonAScrankeMax, Int64 RegioonBScrankeMin, Int64 RegioonBScrankeMax) { var RegioonAMinMax = new KeyValuePair <Int64, Int64>(RegioonAScrankeMin, RegioonAScrankeMax); var RegioonBMinMax = new KeyValuePair <Int64, Int64>(RegioonBScrankeMin, RegioonBScrankeMax); var MengeKandidaat = new KeyValuePair <Int64, KeyValuePair <Int64, Int64> >[] { new KeyValuePair <Int64, KeyValuePair <Int64, Int64> >(RegioonAScrankeMin, RegioonBMinMax), new KeyValuePair <Int64, KeyValuePair <Int64, Int64> >(RegioonAScrankeMax, RegioonBMinMax), new KeyValuePair <Int64, KeyValuePair <Int64, Int64> >(RegioonBScrankeMin, RegioonAMinMax), new KeyValuePair <Int64, KeyValuePair <Int64, Int64> >(RegioonBScrankeMax, RegioonAMinMax), }; var ListeGrenzePunkt = MengeKandidaat // .Where((Kandidaat) => PunktLiigtInRegioon1D(Kandidaat.Value.Key, Kandidaat.Value.Value, Kandidaat.Key)) .Where(Kandidaat => Kandidaat.Value.Key <= Kandidaat.Key && Kandidaat.Key <= Kandidaat.Value.Value) .Select((Kandidaat) => Kandidaat.Key) .ToArray(); var ListeGrenzePunktDistinct = ListeGrenzePunkt.Distinct().ToArray(); return(ListeGrenzePunktDistinct); }
private static bool DoTestsMatchFilterRequest(string[] testTags, KeyValuePair<string, string>[] filterTags) { //If no tags were requested, then then it is a match if (!filterTags.Any()) { return true; } var includeTags = filterTags.Where(t => t.Value.Equals("true", StringComparison.OrdinalIgnoreCase)) .Select(t => t.Key) .ToArray(); var excludeTags = filterTags.Where(t => t.Value.Equals("false", StringComparison.OrdinalIgnoreCase)) .Select(t => t.Key) .ToArray(); return !excludeTags.Intersect(testTags, StringComparer.OrdinalIgnoreCase).Any() && includeTags.Intersect(testTags, StringComparer.OrdinalIgnoreCase).Count() == includeTags.Count(); }
protected RestfulResourceController() { _allResponseFactories = new [] { new KeyValuePair<string, ResponseFactoryDelegate<ActionResult>>("*/*", WildcardResponseFactory), new KeyValuePair<string, ResponseFactoryDelegate<ActionResult>>("text/html", TextHtmlResponseFactory), new KeyValuePair<string, ResponseFactoryDelegate<ActionResult>>("application/json", ApplicationJsonResponseFactory), new KeyValuePair<string, ResponseFactoryDelegate<ActionResult>>("text/xml", TextXmlResponseFactory), }; _responseFactories = _allResponseFactories.Where(f => SupportedAcceptHeaders.Contains(f.Key)); }
private void SavePositions(EstimatedRankings points, Activity isActive) { if (!_positionsRepository.AsQueryable().Where(x => x.ID == _currentSeason.ToString()).Any()) { KeyValuePair <Teams, int?>[] teamPoints = new KeyValuePair <Teams, int?> [44]; for (int i = 0; i < 44; i++) { PropertyInfo propInfo = points.GetType().GetProperty(allTeams[i].Name.Replace(' ', '_').Replace('.', '_')); teamPoints[i] = new KeyValuePair <Teams, int?>(allTeams[i], Convert.ToInt32(propInfo.GetValue(points))); } teamPoints = teamPoints.OrderByDescending(m => m.Value).ToArray(); for (int i = 0; i < teamPoints.Length; i++) { if (teamPoints[i].Value == 0) { teamPoints[i] = new KeyValuePair <Teams, int?>(teamPoints[i].Key, null); } else { teamPoints[i] = new KeyValuePair <Teams, int?>(teamPoints[i].Key, i + 1); } } Positions positions = new Positions(); positions.ID = _currentSeason.ToString(); for (int i = 0; i < allTeams.Length; i++) { int? pkt = teamPoints.Where(m => m.Key == allTeams[i]).First().Value; PropertyInfo propInfo = new Positions().GetType().GetProperty(allTeams[i].Name.Replace(' ', '_').Replace('.', '_')); if (pkt != null && pkt != 0) { propInfo.SetValue(positions, Convert.ToInt32(teamPoints.Where(m => m.Key == allTeams[i]).First().Value)); } else { propInfo.SetValue(positions, null); } } _positionsRepository.Add(positions); _positionsRepository.SaveChanges(); } }
internal void SetValidationResult(ModelStateDictionary state) { var arr = new KeyValuePair <string, ModelState> [state.Values.Count]; state.CopyTo(arr, 0); PostResponseModel.ModelValidation = new ModelValidationOutput { IsValid = state.IsValid, Errors = arr.Where(x => x.Value != null && x.Value.Errors.Any()) .Select(x => new ModelValidationItem(x.Key.IndexOf(".") >= 0 ? x.Key.Substring(x.Key.IndexOf(".") + 1) : x.Key, x.Value.Errors.First().ErrorMessage)) .ToList() }; }
public void CopyTo() { var trie = new StringTrie <bool> { { "ABC", true }, { "AB", false }, { "ADE", true }, { "ABCDE", false } }; var destinationArray = new KeyValuePair <string, bool> [6]; trie.CopyTo(destinationArray, 1); var result = destinationArray.Where(i => i.Key != null).OrderBy(i => i.Key).ToArray(); var expected = new[] { new KeyValuePair <string, bool>("AB", false), new KeyValuePair <string, bool>("ABC", true), new KeyValuePair <string, bool>("ABCDE", false), new KeyValuePair <string, bool>("ADE", true) }; Assert.Equal(new KeyValuePair <string, bool>(), destinationArray[0]); Assert.Equal(new KeyValuePair <string, bool>(), destinationArray[^ 1]);
/// <summary> /// Serializes the navigator popular rooms news. /// </summary> /// <param name="reply">The reply.</param> /// <param name="rooms">The rooms.</param> /// <param name="category">The category.</param> /// <param name="direct">if set to <c>true</c> [direct].</param> public void SerializeNavigatorPopularRoomsNews(ref ServerMessage reply, KeyValuePair<RoomData, uint>[] rooms, int category, bool direct) { if (rooms == null || !rooms.Any()) { reply.AppendInteger(0); return; } List<RoomData> roomsCategory = new List<RoomData>(); foreach (KeyValuePair<RoomData, uint> pair in rooms.Where(pair => pair.Key.Category.Equals(category))) { roomsCategory.Add(pair.Key); if (roomsCategory.Count == (direct ? 40 : 8)) break; } reply.AppendInteger(roomsCategory.Count); foreach (RoomData data in roomsCategory) data.Serialize(reply, false); }
private void Btn_Calculate_Click(object sender, EventArgs e) { //reset prarameters tb_result.Clear(); CalcType = String.Empty; Calculation.Clear(); if (!String.IsNullOrEmpty(tb_entryValue.Text)) { // create map between binary and its equivalent hex code KeyValuePair <string, char>[] bin_hex_map = new KeyValuePair <string, char>[] { new KeyValuePair <string, char>("0000", '0'), new KeyValuePair <string, char>("0001", '1'), new KeyValuePair <string, char>("0010", '2'), new KeyValuePair <string, char>("0011", '3'), new KeyValuePair <string, char>("0100", '4'), new KeyValuePair <string, char>("0101", '5'), new KeyValuePair <string, char>("0110", '6'), new KeyValuePair <string, char>("0111", '7'), new KeyValuePair <string, char>("1000", '8'), new KeyValuePair <string, char>("1001", '9'), new KeyValuePair <string, char>("1010", 'A'), new KeyValuePair <string, char>("1011", 'B'), new KeyValuePair <string, char>("1100", 'C'), new KeyValuePair <string, char>("1101", 'D'), new KeyValuePair <string, char>("1110", 'E'), new KeyValuePair <string, char>("1111", 'F') }; switch (gb_ChoiceValueType1.Controls.OfType <RadioButton>().Where(rb => rb.Checked).First().Name) { case "rb_ValueType1_binary": switch (gb_ChoiceValueType2.Controls.OfType <RadioButton>().Where(rb => rb.Checked).First().Name) { case "rb_ValueType2_decimal": int base1 = 1; int dec_value = 0; int len = tb_entryValue.Text.Length; for (int w = len - 1; w >= 0; w--) { if (tb_entryValue.Text[w] == '1') { dec_value += base1; } base1 *= 2; tb_result.Text = dec_value.ToString(); } CalcType = "binär > dezimal"; break; case "rb_ValueType2_hexadecimal": string bin = tb_entryValue.Text; int l = bin.Length; int t = bin.IndexOf('.'); // length of string before '.' int len_left = t != -1 ? t : l; // add min 0's in the beginning to make // left substring length divisible by 4 for (int u = 1; u <= (4 - len_left % 4) % 4; u++) { bin = '0' + bin; } // if decimal point exists if (t != -1) { // length of string after '.' int len_right = l - len_left - 1; // add min 0's in the end to make right // substring length divisible by 4 for (int u = 1; u <= (4 - len_right % 4) % 4; u++) { bin = bin + '0'; } } int i = 0; string hex = ""; while (true) { // one by one extract from left, substring // of size 4 and add its hex code hex += bin_hex_map.Where(KV => KV.Key == bin.Substring(i, 4)).First().Value; i += 4; if (i == bin.Length) { break; } // if '.' is encountered add it // to result if (bin.ElementAt(i) == '.') { hex += '.'; i++; } } tb_result.Text = hex; CalcType = "binär > hexadezimal"; break; } break; case "rb_ValueType1_decimal": switch (gb_ChoiceValueType2.Controls.OfType <RadioButton>().Where(rb => rb.Checked).First().Name) { case "rb_ValueType2_binary": for (int u = 31; u >= 0; u--) { int k = Convert.ToInt32(tb_entryValue.Text) >> u; if ((k & 1) > 0) { tb_result.AppendText("1"); } else { tb_result.AppendText("0"); } } CalcType = "dezimal > binär"; break; case "rb_ValueType2_hexadecimal": char[] hexaDeciNum = new char[100]; int i = 0; int nb = Convert.ToInt32(tb_entryValue.Text); while (nb != 0) { // temporary variable remainder int temp = 0; // storing remainder in temp temp = nb % 16; // check if temp < 10 if (temp < 10) { hexaDeciNum[i] = (char)(temp + 48); i++; } else { hexaDeciNum[i] = (char)(temp + 55); i++; } nb = nb / 16; } // array in reverse order for (int j = i - 1; j >= 0; j--) { tb_result.AppendText(hexaDeciNum[j].ToString()); } CalcType = "dezimal > hexadezimal"; break; } break; case "rb_ValueType1_hexadecimal": switch (gb_ChoiceValueType2.Controls.OfType <RadioButton>().Where(rb => rb.Checked).First().Name) { case "rb_ValueType2_decimal": string hexVal = tb_entryValue.Text; int len = hexVal.Length; int base1 = 1; int dec_val = 0; for (int i = len - 1; i >= 0; i--) { if (hexVal[i] >= '0' && hexVal[i] <= '9') { dec_val += (hexVal[i] - 48) * base1; // incrementing base1 base1 = base1 * 16; } // converting it to integral 10 - 15 by subtracting 55 from ASCII value else if (hexVal[i] >= 'A' && hexVal[i] <= 'F') { dec_val += (hexVal[i] - 55) * base1; // incrementing base1 base1 = base1 * 16; } tb_result.Text = dec_val.ToString(); } CalcType = "hexadezimal > dezimal"; break; case "rb_ValueType2_binary": string hexaVal = tb_entryValue.Text; string binary = String.Empty; foreach (char c in hexaVal) { binary += bin_hex_map.Where(KVP => KVP.Value == c.ToString().ToUpper().ToCharArray()[0]).First().Key; } tb_result.Text = binary; CalcType = "hexadezimal > binär"; break; } break; } GenerateCalculation(); } else { MessageBox.Show("Sie müssen zuerst einen Eingabewert eintragen.", "Berechnen nicht möglich", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } }
/// <summary> /// Wraps a message in a string builder and outputs it to the <see cref="Console" /> type host before sending it out to /// all Actors. /// </summary> /// <param name="message"></param> private void LogMessage(dynamic message) { var entry = new StringBuilder($"{message.Topic} {{"); // Casting the properties of message for the sake of revealing a Count property. var props = new KeyValuePair <string, object> [((IDictionary <string, object>)message).Count]; // Append the properties ((IDictionary <string, object>)message).CopyTo(props, 0); // Append the props except for the basic ones using JSON syntax. var subsequent = false; foreach (var prop in props .Where(x => x.Key != "Timestamp" && x.Key != "Topic")) { if (subsequent) { entry.Append(", "); } // Some pattern matching to handle value conversion. switch (prop.Value) { case Array arr: { entry.Append($"{prop.Key}: "); if (arr.Length == 0) { entry.Append("[]"); } else { var subsqarr = false; entry.Append("["); foreach (var o in arr) { if (subsqarr) { entry.Append(", "); } entry.Append(o); subsqarr = true; } entry.Append("]"); } break; } default: entry.Append($"{prop.Key}: {prop.Value}"); break; } subsequent = true; } // Finish off and write. entry.Append("}"); // Post message to the general log. Logger.Debug(entry.ToString()); }
public static IEnumerable <KeyValuePair <DateTime, TimeSpan> > GetOpenSlots(DateTime orderReady, IEnumerable <IWorkingHours> openHours, IEnumerable <PublicHoliday> holidays, IEnumerable <Vacation> vacations) { IEnumerable <DateTime> days = Enumerable.Range(0, 365).Select(i => orderReady.Date.AddDays(i)); /*List<DateTime> daysCountingVacation = new List<DateTime>(); * foreach(var day in days) * { * if (vacations.Count(x => x.StartDate.Date <= day && x.EndDate >= day) == 0) * daysCountingVacation.Add(day); * }*/ IEnumerable <DateTime> daysCountingVacation = days.Where(day => vacations.Count(x => x.StartDate.Date <= day && x.EndDate >= day) == 0); //List<KeyValuePair<DateTime, TimeSpan>> preliminarResults = new List<KeyValuePair<DateTime, TimeSpan>>(); var preliminarResultsGroups = daysCountingVacation.Select(day => { var openHoursSlotsInHolidays = holidays.Where(x => x.Date.Date == day.Date); if (openHoursSlotsInHolidays.Count() > 0) { return(openHoursSlotsInHolidays.Where(x => x.OpenHours != null) .Select(x => new KeyValuePair <DateTime, TimeSpan>(day.Add(x.OpenHours.StartingAt), x.OpenHours.Duration))); } else { var ordinaryHours = openHours.Where(x => x.DayId == (int)day.DayOfWeek).Select(x => new KeyValuePair <DateTime, TimeSpan>(day.Add(x.StartingAt), x.Duration)); return(ordinaryHours); } }).ToArray(); IEnumerable <KeyValuePair <DateTime, TimeSpan> > preliminarResults = new KeyValuePair <DateTime, TimeSpan> [0]; for (int i = 0; i < preliminarResultsGroups.Count(); i++) { preliminarResults = preliminarResults.Concat(preliminarResultsGroups[i]); } foreach (var day in daysCountingVacation) { var openHoursSlotsInHolidays = holidays.Where(x => x.Date.Date == day.Date); if (openHoursSlotsInHolidays.Count() > 0) { var holidayHours = openHoursSlotsInHolidays.Where(x => x.OpenHours != null) .Select(x => new KeyValuePair <DateTime, TimeSpan>(day.Add(x.OpenHours.StartingAt), x.OpenHours.Duration)); preliminarResults = preliminarResults.Concat(holidayHours); } else { var ordinaryHours = openHours.Where(x => x.DayId == (int)day.DayOfWeek) .Select(x => new KeyValuePair <DateTime, TimeSpan>(day.Add(x.StartingAt), x.Duration)); preliminarResults = preliminarResults.Concat(ordinaryHours); } } var onlyAfterOrIncludingOrderReady = preliminarResults.Where(x => x.Key.Add(x.Value) > orderReady); IEnumerable <KeyValuePair <DateTime, TimeSpan> > results = new KeyValuePair <DateTime, TimeSpan> [0]; foreach (var item in onlyAfterOrIncludingOrderReady) { if (item.Key <= orderReady) { TimeSpan offset = orderReady.Subtract(item.Key); results = results.Append(new KeyValuePair <DateTime, TimeSpan>(orderReady, item.Value.Subtract(offset))); } else { results = results.Append(item); } } return(results); }
private void ChangeWhereClauseTable(KeyValuePair<DataTable, DataTable>[] tables, ref List<SqlFilterCondition> whereClause) { DataTable prevTable = null; for (int i = 0; i < whereClause.Count; i++) { SqlFilterCondition cond = whereClause[i]; if (cond.Table != prevTable) { var q = tables.Where(t => t.Key.TableName == cond.Table.TableName); if (q.Count() == 1) prevTable = q.ElementAt(0).Value; } if (prevTable != null) { cond.Table = prevTable; whereClause[i] = cond; } } }
private string projectFromArgs(KeyValuePair<string,string>[] arguments) { var sublimeProject = arguments .Where(p => p.Key == "--editor.sublime.project") .Select(p => p.Value) .FirstOrDefault(); return sublimeProject; }
public void CopyTo() { var trie = new Trie<bool>(); trie.Add("ABC", true); trie.Add("AB", false); trie.Add("ADE", true); trie.Add("ABCDE", false); var destinationArray = new KeyValuePair<string, bool>[6]; ((ICollection<KeyValuePair<string, bool>>)trie).CopyTo(destinationArray, 1); var result = destinationArray.Where(i => i.Key != null).OrderBy(i => i.Key).ToArray(); var expected = new[] { new KeyValuePair<string, bool>("AB", false), new KeyValuePair<string, bool>("ABC", true), new KeyValuePair<string, bool>("ABCDE", false), new KeyValuePair<string, bool>("ADE", true) }; Assert.AreEqual(new KeyValuePair<string, bool>(), destinationArray[0]); Assert.AreEqual(new KeyValuePair<string, bool>(), destinationArray[destinationArray.Length - 1]); Assert.IsTrue(expected.SequenceEqual(result)); }
private static void WriteConstants(StringBuilder outputString, HashSet<string> usedConstants, ref KeyValuePair<string,string>[] remainingConstants, string prefix, string constantsName = null, Func<string, bool> additionalAcceptanceConstantFilter = null, Func<string, bool> additionalRejectConstantFilter = null) { if (string.IsNullOrEmpty(constantsName)) constantsName = FormatEnumName(prefix, ""); var constants = remainingConstants.Where(k => (k.Key.StartsWith(prefix) || (additionalAcceptanceConstantFilter != null && additionalAcceptanceConstantFilter(k.Key))) && (additionalRejectConstantFilter == null || additionalRejectConstantFilter(k.Key))).ToArray(); remainingConstants = remainingConstants.Except(constants).ToArray(); outputString.AppendLine(" enum " + constantsName); outputString.AppendLine(" {"); foreach (var c in constants) { string cname = FormatEnumName(c.Key, prefix); while (usedConstants.Contains(cname)) cname += "_"; usedConstants.Add(cname); outputString.AppendFormat(" {0} = {1},", cname, c.Value); outputString.AppendLine(); } outputString.AppendLine(" };"); }