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


C# Dictionary.Where方法代码示例

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


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

示例1: GetLinksAsJs

        private List<string> GetLinksAsJs(
            List<MarriageSon> marriageSons, 
            List<Marriage> marriages,
            Dictionary<long, Tuple<int, string>> personsJsNodes,
            Dictionary<long, Tuple<int, string>> marriageJsNodes)
        {
            var linksAsJs = new List<string>();
            foreach(var marriageSon in marriageSons)
            {
                var marriage = marriages.Where(x => x.id.Equals(marriageSon.marriage_id)).FirstOrDefault();

                var marriageJsId = marriageJsNodes.Where(x => x.Key.Equals(marriage.id)).Select(x => x.Value.Item1).FirstOrDefault();
                var sonJsId = personsJsNodes.Where(x => x.Key.Equals(marriageSon.son_id)).Select(x => x.Value.Item1).FirstOrDefault();
                var husbandJsId = personsJsNodes.Where(x => x.Key.Equals(marriage.husband_id)).Select(x => x.Value.Item1).FirstOrDefault();
                var wifeJsId = personsJsNodes.Where(x => x.Key.Equals(marriage.wife_id)).Select(x => x.Value.Item1).FirstOrDefault();

                var jsText2 = string.Format("{{\"source\": {0}, \"target\": {1}}}",
                    husbandJsId,
                    marriageJsId);
                var jsText3 = string.Format("{{\"source\": {0}, \"target\": {1}}}",
                    wifeJsId,
                    marriageJsId);
                var jsText1 = string.Format("{{\"source\": {0}, \"target\": {1}}}",
                    marriageJsId,
                    sonJsId);

                linksAsJs.AddRange(new string[] { jsText1, jsText2, jsText3 });
            }
            return linksAsJs;
        }
开发者ID:xavierpena,项目名称:family_tree,代码行数:30,代码来源:D3ForceDirectedExporter.cs

示例2: ChangeMealeUnitAttack

        public void ChangeMealeUnitAttack(Model M, Dictionary<int, Units> team)
        {
            int pos0 = 0;
            int pos1 = 0;
            int pos2 = 0;

            if (M.CurrentUnitAttack == 5)
            {
                string tostr = M.CanAttack[4].ToString();
                char[] pos = tostr.ToCharArray();
                try
                {
                    int.TryParse(pos[0].ToString(), out pos0);
                    int.TryParse(pos[1].ToString(), out pos1);
                    int.TryParse(pos[2].ToString(), out pos2);
                }
                catch (Exception e) { }
                var Target = team.Where(z => z.Value.Live == true)
                    .Where(y => y.Key == pos0 || y.Key == pos1 || y.Key == pos2)
                    .OrderBy(x => x.Value.HP)
                    .FirstOrDefault();
                M.PositionUnitOfAttack = Target.Key;
            }
            else if (M.CurrentUnitAttack == 4)
            {
                string tostr = M.CanAttack[3].ToString();
                char[] pos = tostr.ToCharArray();
                try
                {
                    int.TryParse(pos[0].ToString(), out pos0);
                    int.TryParse(pos[1].ToString(), out pos1);

                }
                catch (Exception e) { }

                var Target = team.Where(z => z.Value.Live == true)
                    .Where(y => y.Key == pos0 || y.Key == pos1)
                    .OrderBy(x => x.Value.HP)
                    .FirstOrDefault();
                M.PositionUnitOfAttack = Target.Key;
            }
            else
            {
                string tostr = M.CanAttack[5].ToString();
                char[] pos = tostr.ToCharArray();
                try
                {
                    int.TryParse(pos[0].ToString(), out pos0);
                    int.TryParse(pos[1].ToString(), out pos1);

                }
                catch (Exception e) { }

                var Target = team.Where(z => z.Value.Live == true)
                    .Where(y => y.Key == pos0 || y.Key == pos1)
                    .OrderBy(x => x.Value.HP)
                    .FirstOrDefault();
                M.PositionUnitOfAttack = Target.Key;
            }
        }
开发者ID:rickSanches,项目名称:game,代码行数:60,代码来源:CPU.cs

示例3: ProcessIntSequence

        public static Dictionary<string, double> ProcessIntSequence(List<int> seq, int order, bool normalize)
        {
            var ans = new Dictionary<string, double>();

            for (int i = 0; i < seq.Count - order; i++)
            {
                string nextkey = "v" + string.Join("_", seq.Skip(i).Take(order).Select(s => s.ToString()).ToArray());

                if (ans.ContainsKey(nextkey))
                {
                    if (normalize)
                        ans[nextkey] += (double)100 / (double)seq.Count;
                    else
                        ans[nextkey]++;
                }
                else
                {
                    if (normalize)
                        ans.Add(nextkey, (double)100 / (double)seq.Count);
                    else
                        ans.Add(nextkey, 1);
                }
            }

            if (normalize)
                ans = ans.Where(p => p.Value >= 200 / (double)seq.Count).ToDictionary(p => p.Key, p => p.Value);
            else
                ans = ans.Where(p => p.Value >= 2).ToDictionary(p => p.Key, p => p.Value);

            return ans;
        }
开发者ID:johnnybuggy,项目名称:HOLO1,代码行数:31,代码来源:StatsAnalysis.cs

示例4: Main

 static void Main()
 {
     Console.SetIn(File.OpenText("TextFile1.txt"));
     int n = int.Parse(Console.ReadLine());
     string move1 = Console.ReadLine();
     string move2 = Console.ReadLine();
     Dictionary<int, Turn> Turns = new Dictionary<int, Turn>();
     for (int i = 1; i <= n; i++)
     {
         Turns.Add(i, new Turn() { Number = i} );
     }
     int lastNumber = 0;
     int count = 0;
     int multiplayer = 1;
     while (Turns.Where(t => !t.Value.IsCaptured).ToList().Count > 0)
     {
         var newTurns = Turns.Where(t => !t.Value.IsCaptured).ToList();
         count = newTurns.Count;
         for (int i = 0; i < count; i++)
         {
             lastNumber = newTurns[i].Value.Number;
             Turns[i].IsCaptured = true;
             i += multiplayer;
         }
         multiplayer++;
     }
     Console.WriteLine(lastNumber);
     Console.WriteLine(MakeMoves(move1));
     Console.WriteLine(MakeMoves(move2));
     //work :)
     //Console.WriteLine("bounded");
     //Console.WriteLine("bounded");
 }
开发者ID:smihaylovit,项目名称:TelerikAkademy,代码行数:33,代码来源:Program.cs

示例5: GetChangeLog

        public static IDictionary<Version, ChangeLogVersionDetails> GetChangeLog(Version fromVersion, Version toVersion, XDocument changeLogContent)
        {
            var changeLog = new Dictionary<Version, ChangeLogVersionDetails>();

            foreach (var changeVersion in changeLogContent.Descendants("Version"))
            {
                var changeLogItem = BuildChangeLogItem(changeVersion);
                if (!changeLog.ContainsKey(changeLogItem.Key))
                {
                    changeLog.Add(changeLogItem.Key, changeLogItem.Value);
                }
            }

            if (fromVersion < toVersion && changeLog.Any(x => x.Key > fromVersion && x.Key <= toVersion))
            {
                return changeLog.Where(x => x.Key > fromVersion && x.Key <= toVersion).OrderByDescending(detail => detail.Key).ToDictionary(detail => detail.Key, detail => detail.Value);
            }

            if (fromVersion < toVersion && changeLog.Any() && toVersion > changeLog.Keys.Max())
            {
                return changeLog.Where(x => x.Key == changeLog.Keys.Max()).ToDictionary(detail => detail.Key, detail => detail.Value);
            }

            if (fromVersion < toVersion && toVersion.Revision > 0 && changeLog.Any() && toVersion < changeLog.Keys.Max())
            {
                var versionWithoutRevision = new Version(toVersion.Major, toVersion.Minor, toVersion.Build);
                return changeLog.Where(x => x.Key > versionWithoutRevision).ToDictionary(detail => detail.Key, detail => detail.Value);
            }

            return changeLog.OrderByDescending(detail => detail.Key).ToDictionary(detail => detail.Key, detail => detail.Value);
        }
开发者ID:richard-green,项目名称:Gallifrey,代码行数:31,代码来源:ChangeLogProvider.cs

示例6: GetDiff

        public Diff GetDiff(Dictionary<string, PriceItem> newProds, Dictionary<string, PriceItem> oldProds)
        {
            oldProds = oldProds ?? new Dictionary<string, PriceItem>();

            var diff = new Diff 
            { 
                NewItems = newProds.Where(kvp => !oldProds.ContainsKey(kvp.Key)).ToDictionary(key => key.Key, value => value.Value),
                DeletedItems = oldProds.Where(kvp => !newProds.ContainsKey(kvp.Key)).ToDictionary(key => key.Key, value => value.Value),
                UpdatedItems = newProds.Where(kvp => oldProds.ContainsKey(kvp.Key)).ToDictionary(key => key.Key, value => value.Value)
            };

            var toRemove = new List<string>();
            foreach (var item in diff.UpdatedItems.Values)
            {
                var oldItem = oldProds[item.Reference];
                if (item.WholesalePrice == oldItem.WholesalePrice && item.Active == oldItem.Active && !SameBalance(item, oldItem))
                {
                    toRemove.Add(item.Reference);
                }
            }

            foreach (var reference in toRemove)
            {
                diff.UpdatedItems.Remove(reference);
            }

            return diff;
        }
开发者ID:tonage,项目名称:supplier2presta.service,代码行数:28,代码来源:Differ.cs

示例7: ReturnCache

 public List<Coin> ReturnCache()
 {
     List<Coin> for_return = new List<Coin>();
     //Получаем список всех доступных монет
     Dictionary<Coin, int> avail_coins = new Dictionary<Coin, int>();
     foreach(var item in GetSorted())
     {
         avail_coins.Add(new Coin(item.Key), item.Value);
     }
     //Массив всех доступных номиналов
     int[] values = avail_coins.Where(p => p.Value > 0).OrderByDescending(p => p.Key.Info.Price).Select(p => p.Key.Info.Price).ToArray();
     int i = 0;
     while (_money_cache > 0 && i<values.Length)
     {
         //Сколько нам нужно монет данного номинала
         int need_coins = (int)Math.Floor((double)_money_cache / values[i]);
         //Сколько у нас их есть
         int have_coins=avail_coins.Where(p=>p.Key.Info.Price==values[i]).Select(p=>p.Value).First();
         //Если у нас есть такое кол-во данных монет то возвращаем его, иначе отдаем что есть
         if(need_coins>have_coins)
         {
             need_coins = have_coins;
         }
         List<Coin> ret_coins=_GetCoins(values[i], need_coins);
         for_return.AddRange(ret_coins);
         _money_cache -= VMWallet.GetSum(ret_coins);
         i++;
     }
     return for_return;
 }
开发者ID:klim-kitaev,项目名称:Vending-Machine,代码行数:30,代码来源:VMWallet.cs

示例8: SaveReport

 public void SaveReport(DateTime sessionStart, DateTime sessionEnd, string path, Dictionary<MouseMessage, ulong> mouseUsage, Dictionary<string, ulong> keyboardUsage, Dictionary<string, ulong> windowUsage, ulong mouseMoveLength)
 {
     XDocument xDoc = new XDocument(new XDeclaration("1.0", "", ""),
         new XElement("StatistiksReport",
             new XAttribute("SessionStart", sessionStart.ToString("yyyyMMddHHmmss")),
             new XAttribute("SessionEnd", sessionEnd.ToString("yyyyMMddHHmmss")),
             new XElement("KeyboardEvents",
                 from x in keyboardUsage.Where(x => ((int)x.Key[0]).IsValidXmlChar())
                 select new XElement("Event",
                     new XAttribute("Key", x.Key),
                     new XAttribute("Count", x.Value))),
             new XElement("MouseEvents",
                 from x in mouseUsage.Where(x => x.Key == MouseMessage.WM_LBUTTONUP || x.Key == MouseMessage.WM_RBUTTONUP) // only left or right mouse button events
                 select new XElement("Event",
                     new XAttribute("Code", x.Key.ToString()),
                     new XAttribute("Count", x.Value))),
             new XElement("MouseMetr",
                 from x in mouseUsage.Where(x => x.Key == MouseMessage.WM_MOUSEMOVE)
                 select new XElement("Event",
                     new XAttribute("Code", "Length"),
                     new XAttribute("Count", mouseMoveLength))),
             new XElement("WindowsEvents",
                 from x in windowUsage
                 select new XElement("Event",
                     new XAttribute("ExeName", x.Key.Split('\\').Last()),
                     new XAttribute("ExePath", x.Key),
                     new XAttribute("Count", x.Value)))));
     xDoc.Save(path);
 }
开发者ID:sash13,项目名称:Statistiks,代码行数:29,代码来源:XmlReportService.cs

示例9: Handle

        public void Handle()
        {
            LogHelper.Info<RefreshGroupsHandler>("Refresh started");

            // 1) get the groups from db
            var groups = _repo.GetAll();

            // 2) get the users for each group from db
            var usersPerGroup = _repo.GetAllUsers();

            // 3) query the users in ad for each group (step 1)
            var adGroupedUsers = new Dictionary<int, IEnumerable<EasyADUser>>();
            foreach (var group in groups)
            {
                adGroupedUsers.Add(group.Id, _groupManager.GetUsersInGroup(group.Name));
            }

            var adUsers = GetUniqueAdUsers(adGroupedUsers);
            var backofficeUsers = GetUniqueBackofficeUsers(usersPerGroup).ToList();

            var deleteUsers = backofficeUsers.Select(u => u.Username).Except(adUsers.Select(u => u.Login)).ToList();
            var newUsers = adUsers.Select(u => u.Login).Except(backofficeUsers.Select(u => u.Username)).ToList();

            // Delete the users that aren't any group anymore
            foreach (var name in deleteUsers)
            {
                LogHelper.Info<RefreshGroupsHandler>(string.Format("Removing user '{0}' from backoffice", name));
                var user = backofficeUsers.First(u => u.Username == name);
                _userService.Delete(user, deletePermanently: false);
                _repo.DeleteUser(user.Id);

                backofficeUsers.Remove(user);
            }

            // Create the users that aren't in the backoffice yet
            foreach (var name in newUsers)
            {
                LogHelper.Debug<RefreshGroupsHandler>(string.Format("Creating user '{0}' in backoffice", name));
                var user = adUsers.First(u => u.Login == name);
                var firstGroup = groups.Single(g => g.Id == adGroupedUsers.First(a => a.Value.Contains(user)).Key);
                var backofficeUser = _userService.CreateUserWithIdentity(user.Login, user.Email, _userService.GetUserTypeById(firstGroup.UserType));

                backofficeUser.Name = user.DisplayName;
                backofficeUsers.Add(backofficeUser);
            }

            // Update the current users
            foreach (var user in backofficeUsers)
            {
                var userGroupIds = adGroupedUsers.Where(g => g.Value.Any(u => u.Login == user.Username)).Select(g => g.Key).ToList();
                _repo.SetGroupsForUser(user.Id, userGroupIds);

                var groupsUserIsIn = adGroupedUsers.Where(a => a.Value.Any(u => u.Login == user.Username)).Select(kvp => groups.First(g => g.Id == kvp.Key));
                ConfigureUserRights(user, groupsUserIsIn);
            }

            LogHelper.Info<RefreshGroupsHandler>("Refresh completed");
        }
开发者ID:ThumNet,项目名称:EasyAD,代码行数:58,代码来源:RefreshGroupsHandler.cs

示例10: CreateMockedIDnaDataReader

        static public IDnaDataReader CreateMockedIDnaDataReader(MockRepository mocks, List<TestDatabaseRow> testRowData)
        {
            IDnaDataReader reader = mocks.DynamicMock<IDnaDataReader>();

            if (testRowData != null)
            {
                Dictionary<string, Queue<RowQueueItem>> queuedData = new Dictionary<string, Queue<RowQueueItem>>();

                reader.Stub(x => x.HasRows).Return(true).WhenCalled(x => x.ReturnValue = queuedData.Where(y => y.Value.Count() > 0).Count() > 0);

                bool firstread = true;
                reader.Stub(x => x.Read()).Return(true).WhenCalled(x =>
                {
                    if (!firstread)
                    {
                        // Find the non-empty queues
                        var nq = queuedData.Where(n => n.Value.Count() > 0);

                        // Find the min value of Row in all the RowQueueItems
                        var min = nq.Min(q => q.Value.Min(n => n.Row));

                        // Get all queues that contain a RowQueueItem with Row == min
                        // These are the queues that contain column values for the current
                        // row that need dequeuing
                        var queues = nq.Where(q => q.Value.Min(n => n.Row) == min);

                        foreach (var qd in queues)
                            qd.Value.Dequeue();
                    }
                    firstread = false;
                    // If we still have at least 1 non-empty queue, return true
                    x.ReturnValue = queuedData.Where(y => y.Value.Count() > 0).Count() >= 1;
                });

                int row = 1;
                foreach (TestDatabaseRow o in testRowData)
                {
                    foreach (KeyValuePair<string, object> kv in o.paramAndValues)
                    {
                        string keyName = kv.Key;
                        object objectValue = kv.Value;

                        if (!queuedData.ContainsKey(keyName))
                        {
                            queuedData.Add(keyName, new Queue<RowQueueItem>());
                        }

                        queuedData[keyName].Enqueue(new RowQueueItem { Row = row, ObjectValue = objectValue });
                    }
                    row++;
                }

                QueueValuesToDataReaderCalls(reader, queuedData);
            }

            return reader;
        }
开发者ID:rocketeerbkw,项目名称:DNA,代码行数:57,代码来源:DataReaderFactory.cs

示例11: GetSingleContour

 public Contour GetSingleContour()
 {
     if (Contours.Count == 0){
         throw new Exception("Контуры отсутствуют");
     }
     if (!AllContoursAreCompleted){
         throw new Exception("Все контуры должны быть замкнуты!");
     }
     var boundingBoxes = new Dictionary<int, BoundingBox>();
     for (int i=0; i<Contours.Count; i++){
         boundingBoxes.Add(i, Contours[i].GetBoundingBox());
     }
     var largestBox = boundingBoxes.FirstOrDefault(x => boundingBoxes.Where(y => y.Key != x.Key).All(y => x.Value.Contains(y.Value)));
     var restBoxes = boundingBoxes.Where(x => x.Key != largestBox.Key).ToArray();
     if (largestBox.Value == null) {
         throw new Exception("Контуры не образуют единой области. Дальнейшие вычисления невозможны");
     }
     if (restBoxes.Any(x => restBoxes.Where(y => y.Key != x.Key).Any(y => x.Value.Contains(y.Value)))){
         throw new Exception("Вложенность дырок недопустима. Дальнейшие вычисления невозможны");
     }
     var largestContour = Contours[largestBox.Key];
     largestContour.OrientCounterclockwise();
     for (int i = 0; i < Contours.Count; i++ ){
         if (i != largestBox.Key){
             var contour = Contours[i];
             contour.OrientClockwise();
             var nearestPoints = largestContour.ToDictionary(x => x,
                 x => contour.ToDictionary(y => y, y => Math.Sqrt(Math.Pow(x.X - y.X, 2) + Math.Pow(x.Y - y.Y, 2))).OrderBy(r => r.Value).First()).
                 OrderBy(r => r.Value.Value).First();
             int largeContourPointIndex = nearestPoints.Key.Index;
             int contourPointIndex = nearestPoints.Value.Key.Index;
             for (int j = 0; j < contour.Count - contourPointIndex + 1; j++){
                 Point pt = contour[contourPointIndex - 1 + j].Clone();
                 pt.Index = largeContourPointIndex + 1 + j;
                 largestContour.Insert(pt.Index - 1, pt);
             }
             for (int j = 0; j < contourPointIndex; j++){
                 Point pt = contour[j].Clone();
                 pt.Index = largeContourPointIndex + contour.Count - contourPointIndex + j + 2;
                 largestContour.Insert(pt.Index - 1, pt);
             }
             Point self = largestContour[largeContourPointIndex - 1].Clone();
             int offset = self.Index + contour.Count + 2;
             self.Index = offset;
             largestContour.Insert(self.Index - 1, self);
             for (int j = offset; j < largestContour.Count; j++){
                 largestContour[j].Index = j + 1;
             }
         }
     }
     largestContour.Index = 1;
     Contours.Clear();
     Contours.Add(largestContour);
     return largestContour;
 }
开发者ID:StanislavUshakov,项目名称:NumericalMethods,代码行数:55,代码来源:PointsInputManager.cs

示例12: SortCollection

 /// <summary>
 /// Sort the collection in the proper manner.
 /// </summary>
 internal static Dictionary<string, ListDictionary> SortCollection(Dictionary<string, ListDictionary> collection, string treeLevel, string sortLevel)
 {
     switch (sortLevel)
     {
         case "Alphabet":
             return collection
                 .OrderBy(kvp => kvp.Key)
                 .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
         case "Effort":
             return collection
                 .OrderByDescending(kvp => kvp.Value["effort"])
                 .ThenBy(kvp => kvp.Key) // Sort alphabetically if there is a tie.
                 .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
         case "Priority":
             return collection
                 .OrderByDescending(kvp => kvp.Value["priority"])
                 .ThenBy(kvp => kvp.Key) // Sort alphabetically if there is a tie.
                 .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
         case "Product":
             var missingTeamString = SimpleWorkItem.GetMissingString("Team");
             var missingTeamCollection = collection.Where(kvp => kvp.Key == missingTeamString); // Reference the 'NO TEAM' grouping.
             return collection
                 .Where(kvp => kvp.Key != missingTeamString) // Exclude 'NO TEAM' from sorting.
                 .OrderBy(kvp => kvp.Key != "Atlas")
                 .ThenBy(kvp => kvp.Key != "Anubis")
                 .ThenBy(kvp => kvp.Key != "Proteus")
                 .ThenBy(kvp => kvp.Key != "Shiva")
                 .ThenBy(kvp => kvp.Key != "Janus")
                 .ThenBy(kvp => kvp.Key != "Phoenix")
                 .ThenBy(kvp => kvp.Key != "Brahma")
                 .ThenBy(kvp => kvp.Key != "Loki")
                 .ThenBy(kvp => kvp.Key != "Heimdall")
                 .ThenBy(kvp => kvp.Key != "Vulcan")
                 .ThenBy(kvp => kvp.Key != "Athena")
                 .ThenBy(kvp => kvp.Key != "Ra")
                 .ThenBy(kvp => kvp.Key) // Any unmentioned teams above will be sorted alphabetically.
                 .Concat(missingTeamCollection) // Attach 'NO TEAM' back on.
                 .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
         case "Date":
             const string futureString = "Future";
             var missingString = SimpleWorkItem.GetMissingString(treeLevel);
             var futureCollection = collection.Where(kvp => kvp.Key == futureString); // Reference the Future grouping.
             var missingCollection = collection.Where(kvp => kvp.Key == missingString); // Reference the missing grouping.
             return collection
                 .Where(kvp => kvp.Key != futureString && kvp.Key != missingString) // Exclude Future and missing from sorting.
                 .OrderBy(kvp => kvp.Key.Split('\\').ElementAtOrDefault(0, "Z")) // Sort by Year, using "Z" to place it last if it's missing.
                 .ThenBy(kvp => kvp.Key.Split('\\').ElementAtOrDefault(1, "Z")) // Sort by Quarter, using "Z" to place it last if it's missing.
                 .ThenBy(kvp => kvp.Key.Split('\\').ElementAtOrDefault(2, "Z")) // Sort by Sprint, using "Z" to place it last if it's missing.
                 .Concat(futureCollection) // Attach Future back on.
                 .Concat(missingCollection) // Attach missing back on.
                 .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
         default:
             throw new Exception("Sorting type: " + sortLevel + ", is not supported.");
     }
 }
开发者ID:gustafsonk,项目名称:TFS-Treemap,代码行数:58,代码来源:SortManager.cs

示例13: Main

        static void Main(string[] args)
        {
            Dictionary<string, Car> cars = new Dictionary<string, Car>();

            int n = int.Parse(Console.ReadLine());
            for (int i = 0; i < n; i++)
            {
                var input = Console.ReadLine().Split();

                var model = input[0];
                var engineSpeed = long.Parse(input[1]);
                var enginePower = long.Parse(input[2]);
                var cargoWeight = long.Parse(input[3]);
                var cargoType = input[4];
                var tier1P = double.Parse(input[5]);
                var tier1A = int.Parse(input[6]);
                var tier2P = double.Parse(input[7]);
                var tier2A = int.Parse(input[8]);
                var tier3P = double.Parse(input[9]);
                var tier3A = int.Parse(input[10]);
                var tier4P = double.Parse(input[11]);
                var tier4A = int.Parse(input[12]);

                var engine = new Engine(engineSpeed, enginePower);
                var cargo = new Cargo(cargoWeight, cargoType);

                var tierOne = new Tier(tier1P, tier1A);
                var tierTwo = new Tier(tier2P, tier2A);
                var tierThree = new Tier(tier3P, tier3A);
                var tierFour = new Tier(tier4P, tier4A);
                List<Tier> tiers = new List<Tier> { tierOne, tierTwo, tierThree, tierFour };
                var car = new Car(model, engine, cargo, tiers);
                cars[car.Model] = car;
            }

            var type = Console.ReadLine();
            if (type == "fragile")
            {
                var result = cars.Where(x => x.Value.Tiers.Exists(y => y.TirePressure < 1d));
                foreach (var car in result)
                {
                    Console.WriteLine(car.Key);
                }
            }
            else
            {
                var result = cars.Where(x => x.Value.Engine.EnginePower > 250);
                foreach (var car in result)
                {
                    Console.WriteLine(car.Key);
                }
            }
        }
开发者ID:borko9696,项目名称:SoftwareUniversity,代码行数:53,代码来源:RawData.cs

示例14: Init

        /// <summary>
        /// Inits the viewmodel with the specified sys info, and setups the default categories.
        /// </summary>
        /// <param name="sysInfo">The sys info.</param>
        /// <param name="attachedFiles">path to the attachment</param>
        /// <author>Jurie.smit</author>
        /// <datetime>2013/01/14-09:19 AM</datetime>
        private void Init(SystemInfoTO sysInfo, Dictionary<string, string> attachedFiles)
        {
            Comment = null;

            ServerLogAttachmentPath = attachedFiles.Where(f => f.Key.Equals("ServerLog", StringComparison.CurrentCulture)).Select(v => v.Value).SingleOrDefault();
            StudioLogAttachmentPath = attachedFiles.Where(f => f.Key.Equals("StudioLog", StringComparison.CurrentCulture)).Select(v => v.Value).SingleOrDefault();
            
            Comment = GenerateDefaultComment(sysInfo);
            SetCaretPosition();
            Categories.AddRange(new List<string> { "General", "Compliment", "Feature request", "Bug", "Feedback" });
            if(attachedFiles.Count > 0) SelectedCategory = "Feedback";
        }
开发者ID:FerdinandOlivier,项目名称:Warewolf-ESB,代码行数:19,代码来源:FeedbackViewModel.cs

示例15: Parts

        public ActionResult Parts(int id = 0, int page = 1, int per_page = 10)
        {
            if (id > 0) {
                APICategory category = new APICategory();

                category = CURTAPI.GetCategory(id);
                ViewBag.category = category;

                List<APIPart> parts = CURTAPI.GetCategoryParts(id, page, per_page);

                Dictionary<string, List<APIPart>> ordered_parts = new Dictionary<string, List<APIPart>>();
                foreach (APIPart part in parts) {
                    APIColorCode color_code = CURTAPI.GetColorCode(part.partID);
                    part.colorCode = color_code.code;
                    if (part.pClass.Length > 0) {
                        if (ordered_parts.Keys.Contains(part.pClass)) { // Already added to dictionary
                            List<APIPart> existing_parts = ordered_parts.Where(x => x.Key == part.pClass).Select(x => x.Value).FirstOrDefault<List<APIPart>>();
                            existing_parts.Add(part);
                            ordered_parts[part.pClass] = existing_parts;
                        } else { // New Color Code
                            List<APIPart> new_parts = new List<APIPart>();
                            new_parts.Add(part);
                            ordered_parts.Add(part.pClass, new_parts);
                        }
                    } else {
                        if (ordered_parts.Keys.Contains(category.catTitle.Trim())) { // Already added to dictionary
                            List<APIPart> existing_parts = ordered_parts.Where(x => x.Key == category.catTitle.Trim()).Select(x => x.Value).FirstOrDefault<List<APIPart>>();
                            existing_parts.Add(part);
                            ordered_parts[category.catTitle.Trim()] = existing_parts;
                        } else { // New Color Code
                            List<APIPart> new_parts = new List<APIPart>();
                            new_parts.Add(part);
                            ordered_parts.Add(category.catTitle.Trim(), new_parts);
                        }
                    }
                }
                ViewBag.parts = ordered_parts;

                // We need to figure out if there are going to be more parts to display
                int more_count = CURTAPI.GetCategoryParts(id, page + 1, per_page).Count;
                ViewBag.more_count = more_count;

                ViewBag.page = page;
                ViewBag.per_page = per_page;

                return View();
            } else {
                return RedirectToAction("Index", "Index");
            }
        }
开发者ID:meganmcchesney,项目名称:CURTeCommerce,代码行数:50,代码来源:CategoriesController.cs


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