当前位置: 首页>>代码示例>>C#>>正文


C# Dictionary.ContainsKey方法代码示例

本文整理汇总了C#中Model.Dictionary.ContainsKey方法的典型用法代码示例。如果您正苦于以下问题:C# Dictionary.ContainsKey方法的具体用法?C# Dictionary.ContainsKey怎么用?C# Dictionary.ContainsKey使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Model.Dictionary的用法示例。


在下文中一共展示了Dictionary.ContainsKey方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: AskAnswer

        public IAnswer AskAnswer(IQuestion question)
        {
            var j = 0;

            var choices = new Dictionary<char,IChoice>();
            question.Choices.ForEach(c => choices.Add((char)('a' + j++), c));

            var answerChar = '\0';

            do
            {
                Console.Clear();
                Console.WriteLine("Question: {0}", question.QuestionString);

                foreach (var choice in choices)
                {
                    Console.WriteLine("{0}. {1}", choice.Key, choice.Value.ChoiceText);
                }

                Console.Write("\nAnswer: ");
                var readLine = Console.ReadLine();
                if (readLine == null) continue;

                if (new[] { "back", "b", "oops", "p", "prev" }.Contains(readLine.ToLower()))
                {
                    return question.CreateAnswer(Choice.PREVIOUS_ANSWER);
                }

                answerChar = readLine[0];
            } while (!choices.ContainsKey(answerChar));

            return question.CreateAnswer(choices[answerChar]);
        }
开发者ID:robinkanters,项目名称:quiz-challenge,代码行数:33,代码来源:Program.cs

示例2: GetVisitData

        public static Dictionary<int, List<Visit>> GetVisitData(string path)
        {
            Dictionary<int, List<Visit>> data = new Dictionary<int, List<Visit>>();
            Random r = new Random();

            foreach (string row in File.ReadLines(path))
            {
                string[] split = row.Split(',');

                if (split.Length > 0)
                {
                    int id = int.Parse(split[0]);
                    Visit visit = new Visit(id, r.Next(1, 10), int.Parse(split[2]), DateTime.Parse(split[1]));

                    if (data.ContainsKey(id))
                    {
                        data[id].Add(visit);
                    }
                    else
                    {
                        data.Add(id, new List<Visit>(){visit});
                    }
                }
            }

            return data;
        }
开发者ID:patpaquette,项目名称:Cheo-visits,代码行数:27,代码来源:DataLoader.cs

示例3: ChooseColor

 public override SuggestedMoves ChooseColor(Color[,] board)
 {
     IDictionary<Color, int> count = new Dictionary<Color, int>();
     foreach(MapNode edgeNode in MapBuilder.BuildMap(board).GetNeighbors())
     {
         if (!count.ContainsKey(edgeNode.Color))
         {
             count[edgeNode.Color] = 1;
         }
         else
         {
             count[edgeNode.Color] = count[edgeNode.Color] + 1;
         }
     }
     return new SuggestedMoves(count.OrderByDescending(keyValuePair => keyValuePair.Value).First().Key);
 }
开发者ID:glenwatson,项目名称:Flood-It-Solver,代码行数:16,代码来源:HighestCount.cs

示例4: GetPath

        public SuggestedMoves GetPath(Color[,] board)
        {
            //Get the farthest nodes
            TreeNode head = MapBuilder.BuildTree(board);
            ISet<TreeNode> farthestNodes = new HashSet<TreeNode>();
            int highestDepth = 0;
            foreach (TreeNode node in head.BFS()) //DFS would be better
            {
                int depth = GetDepth(node);
                if (depth > highestDepth)
                {
                    highestDepth = depth;
                    farthestNodes.Clear();
                    farthestNodes.Add(node);
                }
                else if (depth == highestDepth)
                {
                    farthestNodes.Add(node);
                }
            }

            Console.Write("Farthest nodes are ");
            farthestNodes.Select(n => n.Color).ToList().ForEach(c => Console.Write(c + ", "));
            Console.WriteLine("\r\nFarthest node is " + GetDepth(farthestNodes.First()) + " away from the current");

            //get the color that would step towards each color
            IDictionary<Color, int> tally = new Dictionary<Color, int>();
            foreach (TreeNode farthestNode in farthestNodes)
            {
                TreeNode currentNode = farthestNode;
                while (currentNode.Parent != head)
                {
                    currentNode = currentNode.Parent;
                }
                if (!tally.ContainsKey(currentNode.Color))
                {
                    tally.Add(currentNode.Color, 1);
                }
                else
                {
                    tally[currentNode.Color]++;
                }
            }
            SuggestedMoves suggestedMoves = new SuggestedMoves();
            suggestedMoves.AddFirst(new SuggestedMove(tally.OrderByDescending(kvp => kvp.Value).Select(n => n.Key)));
            return suggestedMoves;
        }
开发者ID:glenwatson,项目名称:Flood-It-Solver,代码行数:47,代码来源:MoveTowardsFarthestNodeLogic.cs

示例5: Visit

		public override void Visit(ControllerTreeNode node)
		{
			var type = GenerateTypeDeclaration(@namespace, node.PathNoSlashes + naming.ToActionWrapperName(node.Name));

			occurences = new Dictionary<string, short>();

			// We can only generate empty argument methods for actions that appear once and only once.
			foreach (var child in node.Children)
			{
				if (!(child is ActionTreeNode)) continue;

				if (!occurences.ContainsKey(child.Name))
					occurences[child.Name] = 0;
				
				occurences[child.Name]++;
			}

			typeStack.Push(type);
			base.Visit(node);
			typeStack.Pop();
		}
开发者ID:mgagne-atman,项目名称:Projects,代码行数:21,代码来源:ActionMapGenerator.cs

示例6: MainViewModel

        public MainViewModel()
        {
            // please adjust this to meet your system layout ...
            // obviously this should be changed to load file dialog usage :)
            try
            {
                _movies = DataLoader.ReadItemLabels("u.item");
                _trainData = DataLoader.ReadTrainingData("u.data");
            }
            catch (Exception)
            {
                MessageBox.Show("Error loading data files! Please check ViewModel.cs for file location!", "Error loading files", MessageBoxButton.OK, MessageBoxImage.Error);
                Application.Current.Shutdown();
            }

            Movies = new ObservableCollection<Movie>(_movies.OrderBy(m=>m.Title));
            NewRank = 1;
            RaisePropertyChanged(() => NewRank);
            SelectedMovie = Movies.First();
            RaisePropertyChanged(() => SelectedMovie);

            Ranking = new Dictionary<int, int>();
            AddRankCommand = new RelayCommand(() => {
                if (!Ranking.ContainsKey(SelectedMovie.Id)) {
                    Log += string.Format("{0} - rank: {1}\n", SelectedMovie, NewRank);
                    RaisePropertyChanged(() => Log);
                    Ranking.Add(SelectedMovie.Id, NewRank);
                    Movies.Remove(SelectedMovie);
                    SelectedMovie = Movies.First();
                    RaisePropertyChanged(() => SelectedMovie);
                }
                var rec = Engine.GetRecommendations(_movies, Ranking, _trainData);
                var foo = rec.OrderByDescending(e => e.Rank);//.Where(e => !Ranking.ContainsKey(e.Id));
                Recomendations =new ObservableCollection<Movie>(foo);
                this.RaisePropertyChanged(() => Recomendations);
            });
        }
开发者ID:jitsolutions,项目名称:dotnet-recommend,代码行数:37,代码来源:MainViewModel.cs

示例7: DisposerInfo

		public static string DisposerInfo()
		{
			var info = new Dictionary<string, int>();
			foreach (Disposer disposer in Disposers)
			{
				if (info.ContainsKey(disposer.GetType().Name))
				{
					info[disposer.GetType().Name] += 1;
				}
				else
				{
					info[disposer.GetType().Name] = 1;
				}
			}
			info = info.OrderByDescending(s => s.Value).ToDictionary(p => p.Key, p => p.Value);
			StringBuilder sb = new StringBuilder();
			sb.Append("\r\n");
			foreach (string key in info.Keys)
			{
				sb.Append($"{info[key],10} {key}\r\n");
			}
			
			return sb.ToString();
		}
开发者ID:egametang,项目名称:Egametang,代码行数:24,代码来源:Game.cs

示例8: DataTable_IgnoreGroups

        public JsonResult DataTable_IgnoreGroups(jQueryDataTableParamModel param, List<String> SubjectID = null, List<String> Class = null, List<String> Check = null, String Search = null, String ShowIgnore = null, String ShowNotIgnore = null)
        {
            if (SubjectID != null && Class != null && Check != null)
            {
                OutputHelper.SaveIgnoreGroups(SubjectID, Class, Check, false);
            }

            Dictionary<String, Group> dbGroups = Clone.Dictionary<String, Group>((Dictionary<String, Group>)(CurrentSession.Get("IgnoreGroups") ?? InputHelper.Groups));
            //Dictionary<String, Group> dbGroups = InputHelper.Groups;

            var Groups = from m in dbGroups.Values select m;

            var total = Groups.Count();

            if (!string.IsNullOrEmpty(Search))
            {
                Groups = Groups.Where(m => m.MaMonHoc.ToLower().Contains(Search.ToLower()) || m.TenMonHoc.ToLower().Contains(Search.ToLower()));
            }

            if (ShowIgnore != null && ShowNotIgnore != null)
            {
                if (ShowIgnore == "checked" && ShowNotIgnore != "checked")
                {
                    Groups = Groups.Where(m => m.IsIgnored == true);
                }
                if (ShowIgnore != "checked" && ShowNotIgnore == "checked")
                {
                    Groups = Groups.Where(m => m.IsIgnored == false);
                }
                if (ShowIgnore != "checked" && ShowNotIgnore != "checked")
                {
                    Groups = Groups.Where(m => false);
                }
            }

            var Result = new List<string[]>();

            var MH = (from m in InputHelper.db.This
                      select new
                      {
                          MaMonHoc = m.MaMonHoc,
                          Nhom = m.Nhom,
                      }).Distinct();

            Dictionary<String, List<String>> CheckMH = new Dictionary<string, List<string>>();

            foreach (var m in MH)
            {
                if (CheckMH.ContainsKey(m.MaMonHoc))
                    CheckMH[m.MaMonHoc].Add(m.Nhom);
                else
                    CheckMH.Add(m.MaMonHoc, new List<String> { m.Nhom });
            }

            foreach (var su in Groups.OrderBy(m => m.TenMonHoc))
            {
                if (CheckMH.ContainsKey(su.MaMonHoc))
                {
                    if (!CheckGroup(CheckMH[su.MaMonHoc], su.Nhom.ToString()))
                    {
                        Result.Add(new string[] {
                                            su.MaMonHoc,
                                            su.TenMonHoc,
                                            su.TenBoMon,
                                            su.TenKhoa,
                                            su.Nhom.ToString(),
                                            su.SoLuongDK.ToString(),
                                            su.IsIgnored ? "checked" : "",
                                        }
                                    );
                    }
                }
                else
                {
                    Result.Add(new string[] {
                                            su.MaMonHoc,
                                            su.TenMonHoc,
                                            su.TenBoMon,
                                            su.TenKhoa,
                                            su.Nhom.ToString(),
                                            su.SoLuongDK.ToString(),
                                            su.IsIgnored ? "checked" : "",
                                        }
                                );
                }

            }

            return Json(new
                            {
                                sEcho = param.sEcho,
                                iTotalRecords = Result.Count(),
                                iTotalDisplayRecords = Result.Count(),
                                //iTotalDisplayedRecords = Subjects.Count(),
                                aaData = Result.Skip(param.iDisplayStart).Take(param.iDisplayLength)
                            },
                            JsonRequestBehavior.AllowGet
                        );
        }
开发者ID:NguyenHoangDuy,项目名称:MVC_ESM,代码行数:99,代码来源:ServicesController.cs

示例9: VNetTest

        public void VNetTest()
        {
            StartTest(MethodBase.GetCurrentMethod().Name, testStartTime);

            string newAzureQuickVMName = Utilities.GetUniqueShortName(vmNamePrefix);
            if (string.IsNullOrEmpty(imageName))
                imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows" }, false);

            // Read the vnetconfig file and get the names of local networks, virtual networks and affinity groups.
            XDocument vnetconfigxml = XDocument.Load(vnetConfigFilePath);
            List<string> localNets = new List<string>();
            List<string> virtualNets = new List<string>();
            HashSet<string> affinityGroups = new HashSet<string>();
            Dictionary<string,string> dns = new Dictionary<string,string>();
            List<LocalNetworkSite> localNetworkSites = new List<LocalNetworkSite>();
            AddressPrefixList prefixlist = null;

            foreach (XElement el in vnetconfigxml.Descendants())
            {
                switch (el.Name.LocalName)
                {
                    case "LocalNetworkSite":
                        {
                            localNets.Add(el.FirstAttribute.Value);
                            List<XElement> elements = el.Elements().ToList<XElement>();
                            prefixlist = new AddressPrefixList();
                            prefixlist.Add(elements[0].Elements().First().Value);
                            localNetworkSites.Add(new LocalNetworkSite()
                                {
                                    VpnGatewayAddress = elements[1].Value,
                                    AddressSpace = new AddressSpace() { AddressPrefixes = prefixlist }
                                }
                            );
                        }
                        break;
                    case "VirtualNetworkSite":
                        virtualNets.Add(el.Attribute("name").Value);
                        affinityGroups.Add(el.Attribute("AffinityGroup").Value);
                        break;
                    case "DnsServer":
                        {
                            dns.Add(el.Attribute("name").Value, el.Attribute("IPAddress").Value);
                            break;
                        }
                    default:
                        break;
                }
            }

            foreach (string aff in affinityGroups)
            {
                if (Utilities.CheckRemove(vmPowershellCmdlets.GetAzureAffinityGroup, aff))
                {

                    vmPowershellCmdlets.NewAzureAffinityGroup(aff, locationName, null, null);
                }
            }

            string vnet1 = virtualNets[0];
            string lnet1 = localNets[0];

            try
            {
                vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, newAzureQuickVMName, serviceName, imageName, username, password, locationName); // New-AzureQuickVM
                Console.WriteLine("VM is created successfully: -Name {0} -ServiceName {1}", newAzureQuickVMName, serviceName);

                vmPowershellCmdlets.SetAzureVNetConfig(vnetConfigFilePath);

                foreach (VirtualNetworkSiteContext site in vmPowershellCmdlets.GetAzureVNetSite(null))
                {
                    Console.WriteLine("Name: {0}, AffinityGroup: {1}", site.Name, site.AffinityGroup);
                }

                foreach (string vnet in virtualNets)
                {
                    VirtualNetworkSiteContext vnetsite = vmPowershellCmdlets.GetAzureVNetSite(vnet)[0];
                    Assert.AreEqual(vnet, vnetsite.Name);
                    //Verify DNS and IPAddress
                    Assert.AreEqual(1, vnetsite.DnsServers.Count());
                    Assert.IsTrue(dns.ContainsKey(vnetsite.DnsServers.First().Name));
                    Assert.AreEqual(dns[vnetsite.DnsServers.First().Name], vnetsite.DnsServers.First().Address);

                    //Verify the Gateway sites
                    Assert.AreEqual(1,vnetsite.GatewaySites.Count);
                    Assert.AreEqual(localNetworkSites[0].VpnGatewayAddress, vnetsite.GatewaySites[0].VpnGatewayAddress);
                    Assert.IsTrue(localNetworkSites[0].AddressSpace.AddressPrefixes.All(c => vnetsite.GatewaySites[0].AddressSpace.AddressPrefixes.Contains(c)));

                    Assert.AreEqual(ProvisioningState.NotProvisioned, vmPowershellCmdlets.GetAzureVNetGateway(vnet)[0].State);
                }

                vmPowershellCmdlets.NewAzureVNetGateway(vnet1);

                Assert.IsTrue(GetVNetState(vnet1, ProvisioningState.Provisioned, 12, 60));

                // Set-AzureVNetGateway -Connect Test
                vmPowershellCmdlets.SetAzureVNetGateway("connect", vnet1, lnet1);

                foreach (GatewayConnectionContext connection in vmPowershellCmdlets.GetAzureVNetConnection(vnet1))
                {
                    Console.WriteLine("Connectivity: {0}, LocalNetwork: {1}", connection.ConnectivityState, connection.LocalNetworkSiteName);
//.........这里部分代码省略.........
开发者ID:EmmaZhu,项目名称:azure-sdk-tools,代码行数:101,代码来源:ScenarioTest.cs

示例10: Generate

        public static void Generate(SupermarketChainContext context, DateTime startDate, DateTime endDate)
        {
            var saleReports = context.SaleReports
                .Where(sl => sl.SaleTime >= startDate && sl.SaleTime <= endDate)
                .Select(sl => new
                {
                    Productname = sl.Product.ProductName,
                    Quantity = sl.Quantity,
                    UnitPrice = sl.Product.Price,
                    Location = sl.Product.Vendor.VendorName,
                    SaleDate = sl.SaleTime
                });

            var groupedByDate = new Dictionary<DateTime, HashSet<SaleReportInfo>>();

            foreach (var i in saleReports)
            {
                if (groupedByDate.ContainsKey(i.SaleDate))
                {
                    groupedByDate[i.SaleDate].Add(new SaleReportInfo(i.Productname, i.Quantity, i.UnitPrice, i.Location));
                }
                else
                {
                    var saleReportsHashSet = new HashSet<SaleReportInfo>()
                    {
                        new SaleReportInfo(i.Productname, i.Quantity, i.UnitPrice, i.Location)
                    };
                    groupedByDate.Add(i.SaleDate, saleReportsHashSet);
                }
            }

            Document doc = new Document(iTextSharp.text.PageSize.LETTER, 35, 35, 70, 60);
            PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream("../../../SaleReports.pdf", FileMode.Create));

            doc.Open();

            PdfPTable table = new PdfPTable(5);
            float[] widths = new float[] { 100f, 100f, 100f, 100f, 100f };
            table.WidthPercentage = 100;

            PdfPCell header = new PdfPCell(new Phrase("Aggregated Sales Report"));
            header.Colspan = 5;
            header.HorizontalAlignment = 1;
            table.AddCell(header);

            foreach (var sl in groupedByDate)
            {
                var date = new PdfPCell(new Phrase(String.Format("{0:dd-MMM-yyyy}", sl.Key)));
                date.Colspan = 5;
                date.BackgroundColor = BaseColor.LIGHT_GRAY;
                table.AddCell(date);

                PdfPCell h1 = new PdfPCell(new Phrase("Product"));
                h1.BackgroundColor = BaseColor.GRAY;
                table.AddCell(h1);

                h1 = new PdfPCell(new Phrase("Quantity"));
                h1.BackgroundColor = BaseColor.GRAY;
                table.AddCell(h1);

                h1 = new PdfPCell(new Phrase("Unit Price"));
                h1.BackgroundColor = BaseColor.GRAY;
                table.AddCell(h1);

                h1 = new PdfPCell(new Phrase("Location"));
                h1.BackgroundColor = BaseColor.GRAY;
                table.AddCell(h1);

                h1 = new PdfPCell(new Phrase("Sum"));
                h1.BackgroundColor = BaseColor.GRAY;
                table.AddCell(h1);

                foreach (var s in sl.Value)
                {
                    table.AddCell(s.ProductName);
                    table.AddCell(s.Quantity.ToString());
                    table.AddCell(s.UnitPrice.ToString());
                    table.AddCell(s.Location);
                    table.AddCell(s.Sum.ToString());
                }

                var msg = new PdfPCell(new Phrase(string.Format("Total sum for {0}: ", String.Format("{0:dd-MMM-yyyy}", sl.Key))));
                msg.HorizontalAlignment = 2;
                msg.Colspan = 4;
                table.AddCell(msg);

                var totalSum = sl.Value.Sum(slr => slr.Sum);

                var totalSumCell = new PdfPCell(new Phrase(totalSum.ToString()));
                table.AddCell(totalSumCell);
            }

            doc.Add(table);
            doc.Close();
        }
开发者ID:DB-Apps-Team-Champagne,项目名称:SupermarketsChain,代码行数:95,代码来源:GenerateSalesReportPdf.cs

示例11: QueryMultipleLogics

        /// <summary>
        /// Asks each AILogic for it's vote of color for the next move and chooses the highest vote
        /// </summary>
        private void QueryMultipleLogics()
        {
            Controller controller = GetController();
            Dictionary<Color, int> colorVote = new Dictionary<Color, int>();
            foreach (AILogicWeight logic in _logics)
            {
                SuggestedMoves colorsChosen = logic.Logic.ChooseColor(controller.GetUpdate()); //reaches across other thread to get the current Board

                if (colorsChosen.BestMoves.Any()) //if there are any moves returned
                {
                    Color color = colorsChosen.BestMoves.First();
                    if (!colorVote.ContainsKey(color))
                    {
                        colorVote.Add(color, 0);
                    }
                    colorVote[color] += logic.Weight;
                }
            }

            if (colorVote.Count > 0)
            {
                Color highestVote = colorVote.OrderByDescending(keyValuePair => keyValuePair.Value).First().Key;
                Console.WriteLine(highestVote);
                controller.PickColor(highestVote);
            }
            else
            {
                Console.WriteLine("No colors were suggested!");
            }
        }
开发者ID:glenwatson,项目名称:Flood-It-Solver,代码行数:33,代码来源:AIInput.cs

示例12: GetNextWords

        public Dictionary<string, int> GetNextWords(List<Verse> verses, string text, bool at_word_start, bool with_diacritics)
        {
            Dictionary<string, int> result = new Dictionary<string, int>();
            if (verses != null)
            {
                if (!String.IsNullOrEmpty(text))
                {
                    text = text.Trim();
                    while (text.Contains("  "))
                    {
                        text = text.Replace("  ", " ");
                    }
                    while (text.Contains("+"))
                    {
                        text = text.Replace("+", "");
                    }
                    while (text.Contains("-"))
                    {
                        text = text.Replace("-", "");
                    }

                    if ((this.Title.Contains("Original")) && (!with_diacritics))
                    {
                        text = text.Simplify29();
                    }

                    string[] text_words = text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    if (text_words.Length > 0)
                    {
                        foreach (Verse verse in verses)
                        {
                            string verse_text = verse.Text;
                            if ((this.Title.Contains("Original")) && (!with_diacritics))
                            {
                                verse_text = verse_text.Simplify29();
                            }

                            verse_text = verse_text.Trim();
                            while (verse_text.Contains("  "))
                            {
                                verse_text = verse_text.Replace("  ", " ");
                            }
                            string[] verse_words = verse_text.Split();

                            if (verse_words.Length == verse_words.Length)
                            {
                                for (int i = 0; i < verse_words.Length; i++)
                                {
                                    bool start_of_text_words_found = false;
                                    if (at_word_start)
                                    {
                                        start_of_text_words_found = verse_words[i].Equals(text_words[0]);
                                    }
                                    else
                                    {
                                        start_of_text_words_found = verse_words[i].EndsWith(text_words[0]);
                                    }

                                    if (start_of_text_words_found)
                                    {
                                        if (verse_words.Length >= (i + text_words.Length))
                                        {
                                            // check rest of text_words if matching
                                            bool is_text_matched = true;
                                            for (int j = 1; j < text_words.Length; j++)
                                            {
                                                if (verse_words[j + i] != text_words[j])
                                                {
                                                    is_text_matched = false;
                                                    break;
                                                }
                                            }

                                            if (is_text_matched)
                                            {
                                                // skip text_words
                                                i += text_words.Length;

                                                // add next word to result (if not added already)
                                                if (i < verse_words.Length)
                                                {
                                                    string matching_word = verse_words[i];
                                                    if (!result.ContainsKey(matching_word))
                                                    {
                                                        result.Add(matching_word, 1);
                                                    }
                                                    else
                                                    {
                                                        result[matching_word]++;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
//.........这里部分代码省略.........
开发者ID:ATouhou,项目名称:QuranCode,代码行数:101,代码来源:Book.cs

示例13: getRetByDept

        /// <summary>
        /// GetRetByDept
        /// </summary>
        /// <param name="RetID">Retrieval ID</param>
        /// <returns></returns>
        public List<ReqAllocation> getRetByDept(string RetID)
        {
            int retID = Convert.ToInt32(RetID);
            List<ReqAllocation> reqAllocationList = new List<ReqAllocation>();

            //hashmap-like to store itemID and collated qty
            Dictionary<string, int> itemQtyENGL = new Dictionary<string, int>();
            Dictionary<string, int> itemQtyCPSC = new Dictionary<string, int>();
            Dictionary<string, int> itemQtyCOMM = new Dictionary<string, int>();
            Dictionary<string, int> itemQtyREGR = new Dictionary<string, int>();
            Dictionary<string, int> itemQtyZOOL = new Dictionary<string, int>();

            //obtain list of requisition with specified RetID
            List<Requisition> reqList = ctx.Requisition.Where(x => x.RetID == retID).ToList();

            foreach(Requisition req in reqList)
            {
                //obtain list of requisition detail with ReqID
                List<RequisitionDetail> reqDetailList = ctx.RequisitionDetail.Where(x => x.ReqID == req.ReqID).ToList();

                foreach(RequisitionDetail reqDetail in reqDetailList)
                {
                    if (req.DeptID == "ENGL")
                    {
                        //if itemQty does not contain the item, add item to itemQty
                        if (!itemQtyENGL.ContainsKey(reqDetail.ItemID))
                        {
                            itemQtyENGL.Add(reqDetail.ItemID, (int)reqDetail.IssueQty);
                        }
                        //else if itemQty contains item, add the qty to existing qty
                        else
                        {
                            itemQtyENGL["reqDetail.ItemID"] += (int)reqDetail.IssueQty;
                        }
                    }

                    if (req.DeptID == "CPSC")
                    {
                        //if itemQty does not contain the item, add item to itemQty
                        if (!itemQtyCPSC.ContainsKey(reqDetail.ItemID))
                        {
                            itemQtyCPSC.Add(reqDetail.ItemID, (int)reqDetail.IssueQty);
                        }
                        //else if itemQty contains item, add the qty to existing qty
                        else
                        {
                            itemQtyCPSC["reqDetail.ItemID"] += (int)reqDetail.IssueQty;
                        }
                    }

                    if (req.DeptID == "COMM")
                    {
                        //if itemQty does not contain the item, add item to itemQty
                        if (!itemQtyCOMM.ContainsKey(reqDetail.ItemID))
                        {
                            itemQtyCOMM.Add(reqDetail.ItemID, (int)reqDetail.IssueQty);
                        }
                        //else if itemQty contains item, add the qty to existing qty
                        else
                        {
                            itemQtyCOMM["reqDetail.ItemID"] += (int)reqDetail.IssueQty;
                        }
                    }

                    if (req.DeptID == "REGR")
                    {
                        //if itemQty does not contain the item, add item to itemQty
                        if (!itemQtyREGR.ContainsKey(reqDetail.ItemID))
                        {
                            itemQtyREGR.Add(reqDetail.ItemID, (int)reqDetail.IssueQty);
                        }
                        //else if itemQty contains item, add the qty to existing qty
                        else
                        {
                            itemQtyREGR["reqDetail.ItemID"] += (int)reqDetail.IssueQty;
                        }
                    }

                    if (req.DeptID == "ZOOL")
                    {
                        //if itemQty does not contain the item, add item to itemQty
                        if (!itemQtyZOOL.ContainsKey(reqDetail.ItemID))
                        {
                            itemQtyZOOL.Add(reqDetail.ItemID, (int)reqDetail.IssueQty);
                        }
                        //else if itemQty contains item, add the qty to existing qty
                        else
                        {
                            itemQtyZOOL["reqDetail.ItemID"] += (int)reqDetail.IssueQty;
                        }
                    }

                }
            }

//.........这里部分代码省略.........
开发者ID:a0070011,项目名称:LogicUniversity_StationaryInventory,代码行数:101,代码来源:RetrievalController.cs

示例14: DictionaryAdd

 /// <summary>
 /// 根据输入的字段自动添加修改日志
 /// </summary>
 /// <param name="_classID"></param>
 /// <param name="_itemID"></param>
 /// <param name="_itemName"></param>
 /// <param name="_itemPrice"></param>
 /// <param name="_itemDiscount"></param>
 /// <param name="_itemExtraNote"></param>
 /// <param name="_itemCount"></param>
 private void DictionaryAdd(Dictionary<string, Model.Item> _dictionary, string _classID, string _itemID, string _itemName, string _itemPrice, string _itemDiscount, string _itemExtraNote, string _itemCount )
 {
     if (_dictionary.ContainsKey(_itemName))
     {
         try
         {
             _dictionary[_itemName].ItemPrice = decimal.Parse(_itemPrice);
             _dictionary[_itemName].ItemDiscount = int.Parse(_itemDiscount);
             _dictionary[_itemName].ItemExtraNote = _itemExtraNote;
             _dictionary[_itemName].ItemCount = int.Parse(_itemCount);
         }
         catch (FormatException)
         {
             MessageBox.Show("输入的数值不正确");
         }
     }
     else
     {
         _dictionary.Add(_itemName, new Item(_classID, _itemID, _itemName, decimal.Parse(_itemPrice), int.Parse(_itemDiscount), _itemExtraNote, int.Parse(_itemCount)));
     }
 }
开发者ID:piratf,项目名称:supermarketManageSystem,代码行数:31,代码来源:frmMerchandiseManagement.cs

示例15: VerifyDeployment

        /// <summary>
        /// Verify a deployment exists
        /// </summary>
        private void VerifyDeployment()
        {
            try
            {
                SafeWriteObjectWithTimestamp(Resources.PublishStartingMessage);
                SafeWriteObjectWithTimestamp(Resources.PublishInitializingMessage);

                Dictionary<string, RoleInstance> roleInstanceSnapshot = new Dictionary<string, RoleInstance>();

                // Continue polling for deployment until all of the roles
                // indicate they're ready
                Deployment deployment = new Deployment();
                do
                {
                    deployment = RetryCall<Deployment>(subscription =>
                        Channel.GetDeploymentBySlot(
                            subscription,
                            _hostedServiceName,
                            _deploymentSettings.ServiceSettings.Slot));

                    // The goal of this loop is to output a message whenever the status of a role
                    // instance CHANGES. To do that, we have to remember the last status of all role instances
                    // and that's what the roleInstanceSnapshot array is for
                    foreach (RoleInstance currentInstance in deployment.RoleInstanceList)
                    {
                        // We only care about these three statuses, ignore other intermediate statuses
                        if (String.Equals(currentInstance.InstanceStatus, RoleInstanceStatus.Busy) ||
                            String.Equals(currentInstance.InstanceStatus, RoleInstanceStatus.Ready) ||
                            String.Equals(currentInstance.InstanceStatus, RoleInstanceStatus.Initializing))
                        {
                            bool createdOrChanged = false;

                            // InstanceName is unique and concatenates the role name and instance name
                            if (roleInstanceSnapshot.ContainsKey(currentInstance.InstanceName))
                            {
                                // If we already have a snapshot of that role instance, update it
                                RoleInstance previousInstance = roleInstanceSnapshot[currentInstance.InstanceName];
                                if (!String.Equals(previousInstance.InstanceStatus, currentInstance.InstanceStatus))
                                {
                                    // If the instance status changed, we need to output a message
                                    previousInstance.InstanceStatus = currentInstance.InstanceStatus;
                                    createdOrChanged = true;
                                }
                            }
                            else
                            {
                                // If this is the first time we run through, we also need to output a message
                                roleInstanceSnapshot[currentInstance.InstanceName] = currentInstance;
                                createdOrChanged = true;
                            }

                            if (createdOrChanged)
                            {
                                string statusResource;
                                switch (currentInstance.InstanceStatus)
                                {
                                    case RoleInstanceStatus.Busy:
                                        statusResource = Resources.PublishInstanceStatusBusy;
                                        break;

                                    case RoleInstanceStatus.Ready:
                                        statusResource = Resources.PublishInstanceStatusReady;
                                        break;

                                    default:
                                        statusResource = Resources.PublishInstanceStatusCreating;
                                        break;
                                }

                                SafeWriteObjectWithTimestamp(String.Format(Resources.PublishInstanceStatusMessage,
                                    currentInstance.InstanceName, currentInstance.RoleName, statusResource));

                            }
                        }
                    }

                    // If a deployment has many roles to initialize, this
                    // thread must throttle requests so the Azure portal
                    // doesn't reply with a "too many requests" error
                    Thread.Sleep(int.Parse(Resources.StandardRetryDelayInMs));
                }
                while (deployment.RoleInstanceList.Any(
                    r => r.InstanceStatus != RoleInstanceStatus.Ready));

                if (CanGenerateUrlForDeploymentSlot())
                {
                    SafeWriteObjectWithTimestamp(
                        Resources.PublishCreatedWebsiteMessage,
                        string.Format(Resources.ServiceUrl, _hostedServiceName));
                }
                else
                {
                    SafeWriteObjectWithTimestamp(
                        Resources.PublishCreatedWebsiteLaunchNotSupportedMessage);
                }

            }
//.........这里部分代码省略.........
开发者ID:jt2073,项目名称:azure-sdk-tools,代码行数:101,代码来源:PublishAzureServiceProject.cs


注:本文中的Model.Dictionary.ContainsKey方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。