/*** * Bully class constructor */ public Bully(Dictionary<int, String> candidateMachines) { machines = candidateMachines; n = candidateMachines.Count(); positionValue = new int[candidateMachines.Count()]; for (int i = 0; i < candidateMachines.Count(); i++) { positionValue[i] = candidateMachines.Keys.ElementAt(i); } Console.WriteLine(classNameLog + "New instance of bully generator with machines " + machines); Console.WriteLine(classNameLog + "Key values array" + positionValue); myIp = CSharpRpcServer.getMyIpAddress(); }
public void getFrameVisitFromLevel(List<Visit> listVisit, out HelperFrame.GroupType groupType, out Dictionary<string, List<Visit>> visitByDate) { this.visits = listVisit; groupType = HelperFrame.GroupType.DAY; visitByDate = HelperDate.getVisitsByDate(listVisit, "dd MMM"); if (!isBlend(visitByDate.Count())) { groupType = HelperFrame.GroupType.WEEK; visitByDate = HelperDate.getVisitsByWeek(listVisit); if (!isBlend(visitByDate.Count())) { groupType = HelperFrame.GroupType.MONTH; visitByDate = HelperDate.getVisitsByDate(listVisit, "MMM yyyy"); } } }
public static string AddQueryString( string url, string key, string value) { string result = url; string[] t = url.Split('?'); string path = t[0]; string[] querystring = new string[]{}; if(t.Length > 1) querystring = t[1].Split('&'); Dictionary<string, string> queryParams = new Dictionary<string,string>(); foreach( string q in querystring ){ if( q != string.Empty ) queryParams.Add( q.Split('=')[0], q.Split('=')[1]); } if( queryParams.ContainsKey(key) ) queryParams[key] = value; else queryParams.Add( key, value); result = path; if( queryParams.Count() > 0) { result += "?"; foreach( string k in queryParams.Keys ) result += k + "=" + queryParams[k] + "&"; if (result.EndsWith("&")) result = result.TrimEnd('&'); } return result; }
/// <summary> /// 用户向消息总线注册 /// </summary> public void Register() { //向共享内存中写入数据,进行注册 int pid = Process.GetCurrentProcess().Id; string address = ".\\Private$\\myQueue" + pid; MyLocker.Lock("sm"); try { processDic = (Dictionary<int, string>)sm.Data; } catch (Exception ex) { processDic = new Dictionary<int, string>(); } if (!processDic.ContainsKey(pid)) { processDic.Add(pid, address); sm.Data = processDic; } processDic = (Dictionary<int, string>)sm.Data; localV = sm.Version; MyLocker.Unlock("sm"); Console.WriteLine("客户端数量:" + processDic.Count()); ReceiveNow(); }
private GeoBoundingBoxFilter RetrieveBox(string fieldName, Dictionary<string, object> boxDict) { // maybe are are dealing with the vertices if (boxDict.Count() == 4) return GetBoxFromVertices(fieldName, boxDict); CoordinatePoint topLeft; CoordinatePoint bottomRight; if (boxDict.ContainsKey(_TOP_LEFT)) { topLeft = CoordinatePointSerializer.DeserializeCoordinatePoint(boxDict.GetString(_TOP_LEFT)); bottomRight = CoordinatePointSerializer.DeserializeCoordinatePoint(boxDict.GetString(_BOTTOM_RIGHT)); } else if (boxDict.ContainsKey(_TOP_RIGHT)) { CoordinatePoint topRight = CoordinatePointSerializer.DeserializeCoordinatePoint(boxDict.GetString(_TOP_RIGHT)); CoordinatePoint bottomLeft = CoordinatePointSerializer.DeserializeCoordinatePoint(boxDict.GetString(_BOTTOM_LEFT)); topLeft = new CoordinatePoint(topRight.Latitude, bottomLeft.Longitude); bottomRight = new CoordinatePoint(bottomLeft.Latitude, topRight.Longitude); } else { throw new Exception("No bounding box formed by current properties."); } return new GeoBoundingBoxFilter(fieldName, topLeft, bottomRight); }
private static void ProblemA() { var addressCount = int.Parse(Console.ReadLine()); var addresses = new Dictionary<string, List<string>>(); for (int i = 0; i < addressCount; i++) { var email = Console.ReadLine(); var canonicalEmail = GetCanonicalEmail(email); if (addresses.ContainsKey(canonicalEmail)) addresses[canonicalEmail].Add(email); else addresses.Add(canonicalEmail, new List<string> { email }); } Console.WriteLine(addresses.Count()); foreach (var a in addresses) { Console.Write(a.Value.Count); Console.Write(' '); foreach (var item in a.Value) { Console.Write(item + ' '); } Console.WriteLine(); } }
private void HeaderInfo() { this.Output.AppendLine(Messages.WavesSeparator); if (this.IsLogged) { this.Output.AppendLine(string.Format(Messages.UserWelcomeMessage, this.CurrentUser.Username)); } else { this.Output.AppendLine(string.Format(Messages.GuestWelcomeMessage)); } var allQuestions = this.Questions; var hotQuestions = allQuestions.Sum(question => question.Answers.OfType<BestAnswer>().Count()); var allAnswers = this.Answers; var userAnswers = new Dictionary<string, int>(); foreach (var answer in allAnswers) { var author = answer.Author.Username; if (!userAnswers.ContainsKey(author)) { userAnswers.Add(author, 0); } userAnswers[author]++; } var activeUsers = userAnswers.Count(user => user.Value >= 3); this.Output.AppendLine(string.Format(Messages.GeneralHeaderMessage, hotQuestions, activeUsers)); this.Output.AppendLine(Messages.WavesSeparator); }
/// <summary> /// Constructeur paramétré /// </summary> /// <param name="journees">Liste des journées de la mission</param> public GestionCarte(Dictionary<int, Journee> journees) { InitializeComponent(); this.journees = journees; lieuxADessiner = new List<Lieu>(); TreeNode t = new TreeNode("Tout afficher"); activitesExterieures.Nodes.Add(t); activitesExterieures.SelectedNode = t; for (int i = 1; i <= journees.Count(); ++i) { if (journees[i].isJourneeExterieure()) { TreeNode tn = new TreeNode("Journée " + i); activitesExterieures.Nodes.Add(tn); foreach (Activite a in journees[i].getActivites()) if (a.isActiviteExterieure()) { TreeNode tnn = new TreeNode(a.getNom() + " - " + a.getHeureDebut().getHeures() + "h -> " + a.getHeureFin().getHeures() + "h"); tnn.Tag = a; tn.Nodes.Add(tnn); lieuxADessiner.Add(a.getLieu()); } } } this.Refresh(); }
private static void CharHistogram(string str) { Dictionary<char,int> dict=new Dictionary<char,int>(); foreach (var item in str) { if (dict.ContainsKey(item)) { dict[item] += 1; } else { dict.Add(item, 1); } } int counter = 0; Console.Write("{ "); foreach (var ch in dict) { if (counter==dict.Count()-1) { Console.Write("'" + ch.Key + "'" + ": " + ch.Value + " }"); } else { Console.Write("'" + ch.Key + "'" + ": " + ch.Value + ", "); } counter++; } }
public void Test_Analyze() { var httpClientMock = new Mock<IHttpClient>(); httpClientMock.Setup(it => it.DownloadString(It.IsAny<string>())) .Returns<string>((url) => { return "script"; }); var siteFileProviderMock = new Mock<ISiteFileProvider>(); Dictionary<string, string> styles = new Dictionary<string, string>(); siteFileProviderMock.Setup(it => it.AddFile(It.IsAny<Site>(), It.IsAny<string>(), It.IsAny<string>())) .Callback<Site, string, string>((site1, path, content) => { styles.Add(path, content); }); var scriptAnalyzer = new ScriptAnalyzer(httpClientMock.Object, siteFileProviderMock.Object); var pageHtml = @"<html> <head> <script src=""/script1.js"" type=""text/javascript""></script> <script src=""/script2.js"" type=""text/javascript""></script> </head> <body> </body> </html>"; SiteDownloadContext siteDownloadContext = new SiteDownloadContext(null, new DownloadOptions() { SiteName = "Test_Analyze", Url = "localhost", Pages = 20, Deep = 1 }, null, null); PageDownloadContext pageDownloadContext = new PageDownloadContext(siteDownloadContext, new PageLevel("http://localhost", 1), pageHtml); scriptAnalyzer.Analyze(pageDownloadContext); Assert.AreEqual(2, styles.Count()); Assert.AreEqual("script", styles["\\Scripts\\script1.js"]);
public void AggregatesDataIntoDictionary() { var lastReductionTime = new DateTime(2011, 11, 11, 5, 30, 0, 0); var reduceLevel = new ReduceLevel { Resolution = 5000 }; var sourceAggregationList = new List<MonitorRecord<double>> { new MonitorRecord<double>(new DateTime(2011, 11, 11, 5, 30, 0, 500), 5, 5), new MonitorRecord<double>(new DateTime(2011, 11, 11, 5, 30, 1, 0), 25, 4), new MonitorRecord<double>(new DateTime(2011, 11, 11, 5, 30, 1, 500), 7, 8), new MonitorRecord<double>(new DateTime(2011, 11, 11, 5, 30, 40, 0), 3, 3) }; var destination = new Dictionary<DateTime, IList<MonitorRecord<double>>>(); var aggregater = new RecordReduceAggregate(); var result = aggregater.Aggregate(lastReductionTime, reduceLevel, sourceAggregationList, destination); Assert.Equal(2, destination.Count()); var firstItem = destination.First(); Assert.Equal(new DateTime(2011, 11, 11, 5, 30, 2, 500), firstItem.Key); Assert.Equal(3, firstItem.Value.Count); var lastItem = destination.Last(); Assert.Equal(new DateTime(2011, 11, 11, 5, 30, 42, 500), lastItem.Key); Assert.Equal(1, lastItem.Value.Count); }
private static int BruteForce() { //read Pythagorean Triplets on wikipedia var map = new Dictionary<int, int>(); var sqrt = Math.Sqrt(750000); for (var m = 2; m < sqrt; m++) { for (var n = 1; n < m; n++) { if ((m + n)%2 > 0 && MathUtils.Gcd(m, n) == 1) { var a = m*m - n*n; var b = 2*m*n; var c = m*m + n*n; var d = a + b + c; while (d <= 1500000) { if (!map.ContainsKey(d)) { map.Add(d, 0); } map[d]++; d += a + b + c; } } } } return map.Count(x => x.Value == 1); }
//constructors; public Filler(DMSImage Source) : base(new Size(Source.Width, Source.Height), Source, Color.Gray) { m_pixelindex = new Dictionary<int, int>(); m_pixels = new List<PixelInfo>(); m_resolution = START_RESOLUTION; m_rand = new Random(); double delta = 0; int iter = 0; while (m_pixels.Count < MIN_PIXELS || delta > DELTA_THRESHOLD && iter < MAX_ITERS) { if (iter == MAX_ITERS || delta < DELTA_THRESHOLD) { iter = 0; m_resolution >>= 1; if (m_resolution == 0) break; Console.Write("\n" + m_resolution); //bring on new pixels if necessary for (int u = 0; u < Source.Width; u += m_resolution) { for (int v = 0; v < Source.Height; v += m_resolution) { if (GetPixelHelper(u, v) == null) { PixelInfo newpixel = new PixelInfo(u, v, new Point3D()); newpixel.SetNeighbors(m_Source, m_resolution); SetAvgColour(newpixel); m_pixels.Add(newpixel); m_pixelindex.Add(v * Source.Width + u, m_pixels.Count() - 1); } } } } else { iter++; } Console.Write('.'); //do the averaging! delta = 0.0; if (m_pixels.Count() == 0) continue; for (int i = 0; i < 10000; i++) { int idx = m_rand.Next(m_pixelindex.Count()); idx = m_pixelindex.Keys.ToArray()[idx]; int u = idx % Source.Width; int v = idx / Source.Width; int pixelidx = m_pixelindex[idx]; delta += SetAvgColour(m_pixels[pixelidx]); } } Console.WriteLine(); }
public bool isDrawActive(UserInfo[] userInfos, Skeleton[] skeletons) { Dictionary<int, double> userDistanceList = new Dictionary<int, double>(); foreach (var userInfo in userInfos) { int userID = userInfo.SkeletonTrackingId; if (userID == 0) { continue; } foreach (var skel in skeletons) { double skeletonPosition; if (skel.TrackingId == userID) { skeletonPosition = skel.Position.Z; userDistanceList[userID] = skeletonPosition; } else { continue; } } } if (userDistanceList.Count() == 0) return false; // get id of the closest user double smallest = 100000.0; int UserIdOfClosest = 0; foreach (KeyValuePair<int, double> entry in userDistanceList) { if (entry.Value < smallest) { smallest = entry.Value; UserIdOfClosest = entry.Key; } } if (UserIdOfClosest == 0) { return false; } // check if the closest users action is triggered foreach (var userInfo in userInfos){ if (userInfo.SkeletonTrackingId == UserIdOfClosest) { return modesList.ElementAt(currentModeId).isInteractionActive(userInfo.HandPointers); } else { continue; } } return false; }
internal static double Mean(Dictionary<DateTime, double> returns) { double S = 0; foreach(KeyValuePair<DateTime, double> kvp in returns) { S += kvp.Value; } return S/returns.Count(); }
static void Main(string[] args) { Dictionary<string, string> languagesDictionary = new Dictionary<string, string>(); languagesDictionary.Add("C#", "The best programming language in the world."); Console.WriteLine("This is a dictionary of computer programming languages. To search for a language by it's name press N or to search by description enter D"); Console.WriteLine("Alternatively you can enter C to find out how many languages are held in the dictionary or X to quit."); char userInput = Convert.ToChar(Console.ReadLine().ToLower()); do { switch (userInput) { case 'n': Console.WriteLine("Please enter the name of the language you are searching for."); string searchName = Console.ReadLine(); if (languagesDictionary.ContainsKey(searchName) == true) { Console.WriteLine(searchName + " is in the dictionary."); } else { Console.WriteLine(searchName + " could not be found."); } break; case 'd': Console.WriteLine("Please enter a description of the language you are searching for."); string searchDescription = Console.ReadLine(); if (languagesDictionary.ContainsValue(searchDescription) == true) { Console.WriteLine(searchDescription + " is in the dictionary."); } else { Console.WriteLine(searchDescription + " could not be found."); } break; case 'c': int dictionarySize = languagesDictionary.Count(); Console.WriteLine("There are " + dictionarySize + " languages in the dictionary"); break; default: break; } Console.WriteLine("To search for a language by it's name press N or to search by description enter D. Alternatively you can enter C to find out how many languages are held in the dictionary or X to quit."); userInput = Convert.ToChar(Console.ReadLine().ToLower()); } while (userInput != 'x'); Console.WriteLine("Your session has now ended."); }
public void Dictionary() { /* Dictionary<string, int> people = new Dictionary<string, int>(); people.Add("Emmy", 4); people.Add("Abby", 10); people.Add("Cathy", 45); people.Add("Laffy", 13); people.Add("Daffy", 60); */ //or Dictionary<string, int> people = new Dictionary<string, int>() { { "Emmy", 4}, { "Abby", 10 }, { "Cathy", 45}, { "Laffy", 13}, { "Daffy", 60 }, }; //two ways of checking if a key exists if(people.ContainsKey("Abby")) { int value = people["Abby"]; Console.WriteLine(value); } int value2; if (people.TryGetValue("Laffy", out value2)) { Console.WriteLine(value2); } //print out all keys and values foreach (KeyValuePair<string, int> pair in people) { Console.WriteLine("Key: " + pair.Key + " Value: " + pair.Value); } //or foreach(string key in people.Keys) { Console.WriteLine("Key: " + key); } foreach(int value in people.Values) { Console.WriteLine("Value: " + value); } //get dictionary size Console.WriteLine(people.Count); //or Console.WriteLine(people.Count()); }
/** * Join parameters map into string, usually query string * * @param queryParams Map to join * @param isUri Indicates that value parameters must be uri-encoded * @return Result query string, like k=v&k1=v1 */ public static String joinParams(Dictionary<String, Object> queryParams, bool isUri) { var parameters = new List<string>(queryParams.Count()); parameters.AddRange( queryParams.Select( entry => String.Format("{0}={1}", entry.Key, isUri ? HttpUtility.UrlEncode(Convert.ToString(entry.Value)) : Convert.ToString(entry.Value)))); return join(parameters, "&"); }
public void DownloadLookUp_ValidJson(string json) { StringDownloadLookup downloadLookup = new StringDownloadLookup(json); IDictionary<string,IDictionary<string,int>> packages = downloadLookup.Load(); Assert.True(packages != null & packages.Count() == 2); IDictionary<string,int> versions = new Dictionary<string,int>(); Assert.True(packages.TryGetValue("AutofacContrib.NSubstitute".ToLowerInvariant(), out versions)); Assert.True(versions.Count() == 2); Assert.True(versions.Values.ToArray()[0] == 406 && versions.Values.ToArray()[1] == 137); }
static void Main(string[] args) { Console.WriteLine("loading options..."); options = LoadOptions("options.csv"); mmmOptions = LoadOptions("mmm_candidates.csv"); Console.WriteLine("loading voters..."); var lines = File.ReadAllLines("voters.csv").Skip(1).Select(line => line.Split(';')).ToList(); Console.WriteLine("parsing voters..."); deactivated = lines.ToDictionary(parts => parts[0] + parts[2].Substring(3), parts => parts[3].Contains("Deactivated")); voters = lines.ToDictionary(parts => parts[0] + parts[2].Substring(3), parts => parts[1]); //id+phone => datetime Console.WriteLine("voters: {0}", voters.Count); Console.WriteLine("decrypting..."); var decrypted = new Blowfish(File.ReadAllText("key.txt")).decryptString(File.ReadAllText("protocol.csv")); File.WriteAllText("decrypted.csv", decrypted); Console.WriteLine("filtering..."); var voteLines = decrypted.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).Skip(1).Select(line => line.Split(';')); var votes = voteLines .Select( parts => new { voter = parts[0] + parts[1], //id + phone candidates = parts[2].Split(',').ToArray() }).ToList(); Console.WriteLine("deactivated count: " + deactivated.Count(kv => kv.Value)); // не 0 Console.WriteLine("Votes by deactivated: " + votes.Count(v => deactivated[v.voter])); //0 Console.WriteLine("Voters with more than 45 votes: " + votes.Count(v => v.candidates.Count() > 45)); //0 Console.WriteLine("Voters with duplicated votes: " + votes.Count(v => v.candidates.Distinct().Count() != v.candidates.Count())); //0 Console.WriteLine("Voters with more than 45 UNIQUE votes: " + votes.Count(v => v.candidates.Distinct().Count() > 45)); //0 Console.WriteLine("Banned MMMs: " + votes.Count(v => IsMmm(v.voter, v.candidates))); var results = votes .Where(v => !IsMmm(v.voter, v.candidates) && !deactivated[v.voter]) .SelectMany(v => v.candidates.Distinct()) .GroupBy(cand => cand) .ToDictionary(g => g.Key, g => g.Count()); Console.WriteLine("results:"); foreach (var res in results.OrderByDescending(kv => kv.Value)) { Console.WriteLine(res.Value + "\t" + options[res.Key]); } Console.WriteLine("Elliminate ALL MMM:"); Console.WriteLine("Banned ALL MMMs: " + votes.Count(v => IsMmmAll(v.voter, v.candidates))); Console.WriteLine("results:"); var results2 = votes .Where(v => !IsMmmAll(v.voter, v.candidates) && !deactivated[v.voter]) .SelectMany(v => v.candidates.Distinct()) .GroupBy(cand => cand) .ToDictionary(g => g.Key, g => g.Count()); foreach (var res in results2.OrderByDescending(kv => kv.Value)) { Console.WriteLine(res.Value + "\t" + options[res.Key]); } }
internal static double WeightedSum(Dictionary<DateTime, double> ret1, Dictionary<DateTime, double> ret2, double lambda) { if (ret1.Count() != ret2.Count()) throw new ArgumentException("dictionnaire de taille différentes."); double S = 0; int i = 0; foreach(KeyValuePair<DateTime, double> kvp in ret1) { S += Math.Pow(lambda, i)*ret1[kvp.Key]*ret2[kvp.Key]; i+=1; } return S; }
public void DownloadLookUp_NoExceptionThrownWithDuplicateKeys(string json) { StringDownloadLookup downloadLookup = new StringDownloadLookup(json); IDictionary<string, IDictionary<string, int>> packages = downloadLookup.Load(); // Dict should have only one entry when there are duplicate entries. Assert.True(packages != null & packages.Count() == 1); IDictionary<string, int> versions = new Dictionary<string, int>(); Assert.True(packages.TryGetValue("AutofacContrib.NSubstitute".ToLowerInvariant(), out versions)); Assert.True(versions.Count() == 2); // When duplicate entries are present,the first one should be taken and the consecutive ones should be ignored. Assert.True(versions.Values.ToArray()[0] == 406 && versions.Values.ToArray()[1] == 137); }
public ImportResult Import() { if (String.IsNullOrEmpty(_importFileName)) return ImportResult.ImportFileMissing; if (String.IsNullOrEmpty(_outputFileName)) return ImportResult.OutputFileMissing; if (_importFileName.Substring(_importFileName.Length - 4, 4) != ".csv") return ImportResult.BadInputFileType; string[] allRows = File.ReadAllLines(_importFileName); Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); var configSectionGroup = config.GetSectionGroup("transformationRules") as TransformationRuleGroup; if (configSectionGroup != null) { _transformationRules = new List<TransformationRule>(); if (configSectionGroup.InitialsTransformation != null) _transformationRules.Add(configSectionGroup.InitialsTransformation); if (configSectionGroup.BirthDateTransformation != null) _transformationRules.Add(configSectionGroup.BirthDateTransformation); } var transformedRows = TransformRows(allRows, _transformationRules); SourceHeaders = GetSourceHeaders(transformedRows); ColumnsToSkip = GetColumnsToSkip(SourceHeaders); var columnCount = SourceHeaders.Count(); if (columnCount == 0) return ImportResult.BadFormat; var rows = GetRows(transformedRows); if (rows.Count(c => c.Count() != columnCount) > 0) return ImportResult.BadFormat; var encryptedRows = EncryptRows(rows); try { var writer = new StreamWriter(_outputFileName); writer.WriteLine(string.Join(columnSeparator.ToString(), SourceHeaders.Select(c => c.Value))); encryptedRows.ForEach(writer.WriteLine); writer.Flush(); writer.Close(); } catch (IOException e) { return ImportResult.WriteAccessDenied; } return ImportResult.Success; }
public void DownloadLookUp_InvalidEntriesIgnored(string json) { StringDownloadLookup downloadLookup = new StringDownloadLookup(json); IDictionary<string, IDictionary<string, int>> packages = downloadLookup.Load(); // Out of two entries one is invalid. So dict count should be 1. Assert.True(packages != null & packages.Count() == 1); IDictionary<string, int> versions = new Dictionary<string, int>(); Assert.False(packages.TryGetValue("AutofacContrib.NSubstitute".ToLowerInvariant(), out versions)); Assert.True(packages.TryGetValue("Assman.Core".ToLowerInvariant(), out versions)); Assert.True(versions.Count() == 1); // When duplicate entries are present,the first one should be taken and the consecutive ones should be ignored. Assert.True(versions.Values.ToArray()[0] == 138 && versions.Keys.ToArray()[0] == "2.0.7"); }
static void Main(string[] args) { Customer cust1 = new Customer() { ID = 1, Name = "Sowmya", Gender = "Female" }; Customer cust2 = new Customer() { ID = 2, Name = "Mukund", Gender = "Male" }; Customer cust3 = new Customer() { ID = 3, Name = "Vishnu", Gender = "Male" }; Dictionary<int, Customer> dictioncustomers = new Dictionary<int, Customer>(); dictioncustomers.Add(cust1.ID, cust1); dictioncustomers.Add(cust2.ID, cust2); dictioncustomers.Add(cust3.ID, cust3); Customer customer1 = dictioncustomers[1]; Console.WriteLine("id = {0}, Name = {1}, Gender = {2}", customer1.ID, customer1.Name, customer1.Gender); foreach (KeyValuePair<int, Customer> custkeyvaluepair in dictioncustomers) { Console.WriteLine("key is {0}", custkeyvaluepair.Key); Customer cust = custkeyvaluepair.Value; Console.WriteLine("id = {0}, Name = {1}, Gender = {2}", cust.ID, cust.Name, cust.Gender); Console.WriteLine("_____________________________________________________________________"); } foreach(int key in dictioncustomers.Keys) { Console.WriteLine(key); } foreach (Customer custy in dictioncustomers.Values) { Console.WriteLine("id = {0}, Name = {1}, Gender = {2}", custy.ID, custy.Name, custy.Gender); } if (dictioncustomers.ContainsKey(5)) { Customer cust5 = dictioncustomers[5]; } Console.WriteLine("total items={0} ", dictioncustomers.Count(kvp => kvp.Value.ID > 0)); // dictioncustomers.Remove(119); to remove item with key 119 //dictioncustomers.clear(); to remove all items. Customer[] custs = new Customer[3]; custs[0] = cust1; custs[1] = cust2; custs[2] = cust3; Dictionary<int, Customer> customers = custs.ToDictionary(cust => cust.ID, cust => cust); foreach (KeyValuePair<int, Customer> kvp in customers) { Console.WriteLine("key is {0}", kvp.Key); Customer custys = kvp.Value; Console.WriteLine("id is {0}, Name = {1}", custys.ID, custys.Name); } }
static void Main(string[] args) { Dictionary<char, int> alphabet = new Dictionary<char, int>(); string key = Console.ReadLine(); foreach (char letter in key) { if (!alphabet.ContainsKey(letter)) { alphabet.Add(letter, 0); } alphabet[letter]++; } int oddNumber = alphabet.Count(pair => pair.Value % 2 == 1); Console.WriteLine(oddNumber > 1 ? "NO" : "YES"); }
public int countRareNotes3(int[] notes) { var counters = new Dictionary<int, int>(); foreach (var note in notes) { if (counters.ContainsKey(note)) { counters[note]++; } else { counters[note] = 1; } } return counters.Count(x => x.Value == 1); }
private void DrawHeader() { StringBuilder sb = new StringBuilder(); sb.AppendLine("~~~~~~~~~~~~~~~~~~~~"); sb.AppendLine(!base.IsLogged ? Messages.GuestWelcomeMessage : string.Format(Messages.UserWelcomeMessage, this.CurrentUser.Username)); int hotQuestionCount = base.Questions .Count(q => q.Answers .Any(a => a.GetType() == typeof (BestAnswer)) ); int activeUsersCount = 0; var userActivity = new Dictionary<IUser, int>(); base.Questions .ToList() .ForEach(q => { q.Answers .ToList() .ForEach(a => { var answerAuthor = a.Author; if (!userActivity.ContainsKey(answerAuthor)) userActivity.Add(answerAuthor, 0); userActivity[answerAuthor]++; }); }); activeUsersCount = userActivity .Count(g => g.Value >= 3); sb.AppendLine(string.Format(Messages.GeneralHeaderMessage, hotQuestionCount, activeUsersCount)); sb.AppendLine("~~~~~~~~~~~~~~~~~~~~"); Console.WriteLine(sb.ToString().Trim()); }
/// <summary> /// Determine whether this member is a full or partial match /// (or no match) for the set of words that is passed in /// </summary> /// <param name="line">a set of words that is part of a scenario</param> /// <returns></returns> public NameMatch GetMatch(string line) { var words = _scenarioLineParser.ExtractWordsFromScenarioLine(line); // can't match if not enough words to fill us up if (words.Count < _wordFilters.Count) return null; var paramValues = new Dictionary<string, object>(); var wordIndex = 0; // check each word for a match for (int i = 0; i < _wordFilters.Count; i++) { var wordMatch = _wordFilters[i].GetMatch(words.Skip(wordIndex).ToArray()); if (!wordMatch.IsMatch) return null; // if this is a parameter, add to our hash so we can resolve the (string) value later var paramFilter = _wordFilters[i] as ParameterMatchWordFilter; if (paramFilter != null) paramValues.Add(paramFilter.ParameterName, wordMatch.Value); wordIndex += wordMatch.WordCount; } var match = BuildNameMatch(words, paramValues); if (match != null) { DebugTrace.Trace("Method name match", "Method = " + _methodInfo.DeclaringType.Name + "." +_methodInfo.Name); if (paramValues.Count() > 0) { var paramValueString = string.Join(",", match.ParamValues.Select(kvp => kvp.Key + ":" + kvp.Value). ToArray()); DebugTrace.Trace("Method name match", "Params= " + paramValueString); } } return match; }
public static string ParametersToString(Dictionary<string, string> parameters) { string output = String.Empty; if(parameters != null && parameters.Count>0) { output += "?"; int i = 0; foreach(var parameter in parameters) { output += parameter.Key + "=" + parameter.Value; output += (i != parameters.Count() - 1) ? "&" : ""; i++; } } return output; }