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


C# ConcurrentBag.OrderBy方法代码示例

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


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

示例1: GetLists

        public List<LibraryList> GetLists(int? limit = null)
        {
            var lists = new ConcurrentBag<LibraryList>();

            Directory.EnumerateFiles(_folderPath, "*.xml").AsParallel().ToList().ForEach(file => lists.Add(GetLibraryListFromXmlFile(file)));

            //lists.ToList().ForEach(liblist => { if (liblist != null) AddContentToList(liblist); });

            return limit != null 
                ? lists.OrderBy(list => list.Priority).Take((int)limit).ToList() 
                : lists.OrderBy(list => list.Priority).ToList();
        }
开发者ID:khellang,项目名称:Solvberget,代码行数:12,代码来源:LibraryListXmlRepository.cs

示例2: NormalizeColumns

 public Matrix<double> NormalizeColumns(Matrix<double> dataToNormalize, IList<int> columnsToNormalize = null)
 {
     columnsToNormalize = columnsToNormalize ?? Enumerable.Range(0, dataToNormalize.ColumnCount).ToList();
     var normalizedColumns = new ConcurrentBag<Tuple<int, Vector<double>>>();
     var columnStds = new double[dataToNormalize.ColumnCount];
     var columnMeans = new double[dataToNormalize.ColumnCount];
     for (int colIdx = 0; colIdx < dataToNormalize.ColumnCount; colIdx++)
     {
         columnStds[colIdx] = dataToNormalize.Column(colIdx).StandardDeviation();
         columnMeans[colIdx] = dataToNormalize.Column(colIdx).Mean();
     }
     Parallel.For(0, dataToNormalize.ColumnCount, colIdx =>
     {
         Vector<double> vectorToAdd;
         if (!columnsToNormalize.Contains(colIdx))
         {
             vectorToAdd = dataToNormalize.Column(colIdx);
         }
         else
         {
             var columnVector = dataToNormalize.Column(colIdx);
             var columnStd = columnStds[colIdx];
             var columnMean = columnMeans[colIdx];
             vectorToAdd = columnVector.Subtract(columnMean).Divide(columnStd);
         }
         normalizedColumns.Add(new Tuple<int, Vector<double>>(colIdx, vectorToAdd));
     });
     return Matrix<double>.Build.DenseOfColumnVectors(normalizedColumns.OrderBy(tpl => tpl.Item1).Select(tpl => tpl.Item2));
 }
开发者ID:Animattronic,项目名称:BrainSharper,代码行数:29,代码来源:StandardDeviationNormalizer.cs

示例3: Main

        static void Main(string[] args)
        {
            // Get all abundant numbers
            Console.WriteLine("Getting abundant numbers.");
            var abNums = GetAbundantNumbers();
            var results = new ConcurrentBag<int>();
            Console.WriteLine("Processing sums of abundant numbers.");
            Parallel.ForEach(Enumerable.Range(1, 28122), n =>
            {
                int mid = (int)Math.Floor(n / 2.0) + 1;
                bool exp = false;
                foreach (var i in abNums.Where(abNum => abNum <= mid))
                {
                    int remainder = n - i;
                    if (abNums.Contains(remainder))
                    {
                        exp = true;
                        break;
                    }
                }
                if (!exp)
                {
                    results.Add(n);
                }
            });

            foreach (var r in results.OrderBy(v => v))
            {
                Console.WriteLine(r);
            }
            Console.WriteLine("Result: {0}", results.Sum());
            Console.ReadKey();
        }
开发者ID:RichTeaMan,项目名称:EulerProblems,代码行数:33,代码来源:Program.cs

示例4: finish_successfully

        public void finish_successfully()
        {
            var handling = new AsyncHandling(ObjectMother.InvocationContext());
            var list = new ConcurrentBag<string>();

            var task1 = Task.Factory.StartNew(() => {
                Thread.Sleep(100);
                list.Add("A");
            });

            var task2 = Task.Factory.StartNew(() => {
                Thread.Sleep(100);
                list.Add("B");
            });

            var task3 = Task.Factory.StartNew(() => {
                Thread.Sleep(100);
                list.Add("C");
            });

            handling.Push(task1);
            handling.Push(task2);
            handling.Push(task3);

            handling.WaitForAll();

            list.OrderBy(x => x).ShouldHaveTheSameElementsAs("A", "B", "C");
        }
开发者ID:RyanHauert,项目名称:FubuTransportation,代码行数:28,代码来源:AsynchHandlingTester.cs

示例5: HistoricalData

        public IEnumerable<HistoricalResults> HistoricalData(String realm, String faction, Int32 itemID, DateTime startTime, DateTime endTime, double percentile = .25)
        {
            var auctions = (from auc in wac.Auctions
                            where auc.MyAuctionHouse.Realm == realm
                               && auc.MyAuctionHouse.Faction == faction
                               && auc.MyItem.ID == itemID
                               && auc.TimeStamp >= startTime
                               && auc.TimeStamp < endTime
                                // I work with buyouts, not concerned with bid only operations
                               && auc.Buyout > 0
                            group auc by auc.TimeStamp into t
                            select t).ToList();

            ConcurrentBag<HistoricalResults> bag = new ConcurrentBag<HistoricalResults>();
            Parallel.ForEach(auctions, (iTimeStamp) =>
            {
                HistoricalResults hr = new HistoricalResults();
                hr.TimeStamp = iTimeStamp.Key;
                hr.Count = iTimeStamp.Count();
                var buyouts = iTimeStamp.SelectMany(a =>
                    {
                        return Enumerable.Range(0, a.Quanity).Select(b => a.Buyout / a.Quanity);
                    }
                );
                var culledAuctions = buyouts.OrderBy(buy => buy).Take((int)Math.Ceiling(hr.Count * percentile));

                hr.Min = culledAuctions.Min();
                hr.Mean = culledAuctions.Average();

                bag.Add(hr);
            });

            return bag.OrderBy(a => a.TimeStamp).ToList();
        }
开发者ID:TheRealSplith,项目名称:WoWEcon,代码行数:34,代码来源:AuctionAPIController.cs

示例6: GetSubTextPositions

		public static ICollection<int> GetSubTextPositions(string text, string subText)
		{
			if (string.IsNullOrEmpty(text))
			{
				throw new ArgumentException(nameof(text));
			}

			if (string.IsNullOrEmpty(subText))
			{
				throw new ArgumentException(nameof(subText));
			}

			if (subText.Length > text.Length)
			{
				return new List<int>(0);
			}

			text = text.ToLower();
			subText = subText.ToLower();

			var positions = new ConcurrentBag<int>();

			Parallel.For(0, text.Length,
				position =>
					{
						var matchFound = IsSubTextOnPosition(position, text, subText);

						if (matchFound)
						{
							positions.Add(position + 1);
						}
					});

			return positions.OrderBy(x => x).ToList();
		}
开发者ID:skorunka,项目名称:Eviivo.TextMatch,代码行数:35,代码来源:StringUtilities.cs

示例7: ForEachParallelTest

 public void ForEachParallelTest()
 {
     var Builder = new ConcurrentBag<int>();
     int[] Temp = { 0, 0, 1, 2, 3 };
     Temp.ForEachParallel(x => Builder.Add(x));
     Assert.Equal(5, Builder.Count);
     var OrderedString = new string(Builder.OrderBy(x => x).ToString(x => x.ToString(), "").ToArray());
     Assert.Equal("00123", OrderedString);
 }
开发者ID:modulexcite,项目名称:Craig-s-Utility-Library,代码行数:9,代码来源:IEnumerableExtensions.cs

示例8: Main

        /// <summary>
        /// メイン関数
        /// </summary>
        /// <param name="args">編集するファイル郡</param>
        static void Main(string[] args)
        {
            var regexName = new FileInfo(Assembly.GetEntryAssembly().Location).DirectoryName + @"\" + "regex.conf";

            //除外リストを取得
            if(!File.Exists(regexName)) { return; }
            var regexs = File.ReadAllText(regexName)
                .Replace("\r\n", "\n")
                .Split('\n')
                .Where(s => s != "")
                .Where(s => !Regex.IsMatch(s,"^###"))
                .ToList();

            //再帰処理
            args.ToList().ForEach(fileName => {
                if(!File.Exists(fileName)) { return; }
                Console.WriteLine(fileName);
                var time = DateTime.Now;

                //ファイル変換
                Console.WriteLine("File reading");
                var consoleLock = new object();
                var safeBag = new ConcurrentBag<StringContainer>();
                Func<string, bool> action = s => regexs.Any(x => Regex.IsMatch(s, x));

                using(var fs = new StreamReader(fileName)) {
                    Parallel.ForEach(YieldReadToEnd(fs), x => {
                        if((x.Number % 100000) == 0x0000) {
                            lock(consoleLock)
                                Console.WriteLine("line {0}", x.Number);
                        }
                        if(action(x.String))
                            return;
                        safeBag.Add(x);
                    });
                }
                Console.WriteLine(DateTime.Now - time);

                //ファイル出力
                Console.WriteLine("File writing");
                var fInfo = new FileInfo(fileName);
                var str = string.Join("\n", safeBag
                    .OrderBy(x => x.Number)
                    .Select(x => x.String));
                using(var fs = new StreamWriter(fInfo.DirectoryName + @"\" + "整形後" + fInfo.Name)) {
                    fs.Write(str);
                }

                Console.WriteLine(DateTime.Now - time);
                Console.WriteLine();
            });

            Console.Read();
        }
开发者ID:kagerouttepaso,项目名称:LogCleaner,代码行数:58,代码来源:Program.cs

示例9: Index

        public ActionResult Index(String faction = "horde", String realm = "bonechewer", Int32 count = 20, Int32 results = 25, Int32 buymin = 250)
        {
            var StartDate = DateTime.Today.Subtract(new TimeSpan(3, 0, 0, 0));

            // EqulityComparer for Item
            var itemComparer = new GenericEqualityComparer<Item>(
                (a, b) => a.ID == b.ID,
                (a) => a.GetHashCode()
            );
            // Get a set of Item:IE<Auction>
            var items = (from a in wac.Auctions
                           where a.MyAuctionHouse.Realm == realm
                              && a.MyAuctionHouse.Faction == faction
                              && a.TimeStamp >= StartDate
                              && a.TimeStamp <= DateTime.Now
                              && a.Buyout > 0
                           select a.MyItem).ToList();

            items = items.Distinct(itemComparer).ToList();

            // result collection
            ConcurrentBag<AuctionSummary> bag = new ConcurrentBag<AuctionSummary>();
            Parallel.ForEach(items, new ParallelOptions { MaxDegreeOfParallelism = 8 }, (itemAuctions) =>
                {
                    AuctionSummary ret = new AuctionSummary();
                    AuctionAPIController api = new AuctionAPIController();

                    var result = api.SingleZStats(realm, faction, itemAuctions.ID, StartDate, DateTime.Now, .15, 250);

                    // If there is no variance, there is no volatility
                    if (result.StdDev != 0.0 && result.AvgSeen >= count)
                    {
                        ret.ItemID = itemAuctions.ID;
                        ret.ItemName = itemAuctions.Name;
                        ret.Mean = Math.Round(result.Mean, 4);
                        ret.MinBuyout = result.CurrMin;
                        ret.StdDev = Math.Round(result.StdDev, 4);
                        ret.ZValue = Math.Round(result.ZValue, 4);

                        bag.Add(ret);
                    }
                }
            );

            var vmIndex = new HomeIndexVM() { Faction = faction, Realm = realm };
            vmIndex.Items = bag.OrderBy(a => a.ZValue).Take(results).ToList();

            ViewData["faction"] = faction;
            ViewData["realm"] = realm;

            return View(vmIndex);
        }
开发者ID:TheRealSplith,项目名称:WoWEcon,代码行数:52,代码来源:HomeController.cs

示例10: Build

        public UiArchives Build()
        {
            string[] lists = _gameLocation.EnumerateListingFiless().ToArray();
            ConcurrentBag<UiArchiveNode> nodes = new ConcurrentBag<UiArchiveNode>();

            Parallel.ForEach(lists, fileName =>
            {
                ArchiveAccessor accessor = new ArchiveAccessor(GetBinaryFilePath(fileName), fileName);
                nodes.Add(new UiArchiveNode(accessor, null));
            });

            return new UiArchives(nodes.OrderBy(n=>n.Name).ToArray());
        }
开发者ID:truongan012,项目名称:Pulse,代码行数:13,代码来源:UiArchiveTreeBuilder.cs

示例11: GetAbundantNumbers

 private static HashSet<int> GetAbundantNumbers()
 {
     ConcurrentBag<int> conAbNums = new ConcurrentBag<int>();
     Parallel.ForEach(Enumerable.Range(2, 28122), n =>
     {
         var divs = GetDivisors(n);
         var sum = divs.Where(num => num != n).Sum();
         if (sum > n)
             conAbNums.Add(n);
     });
     var abNums = new HashSet<int>(conAbNums.OrderBy(v => v));
     return abNums;
 }
开发者ID:RichTeaMan,项目名称:EulerProblems,代码行数:13,代码来源:Program.cs

示例12: OutputCountItem

        public void OutputCountItem(ConcurrentBag<Task> tasks, ConcurrentQueue<int> concurrentQueue)
        {
            Console.WriteLine();
            foreach (var task in tasks.OrderBy(id => id.Id))
            {
                Console.WriteLine("Поток № {0} - количество элементов  в контейнере {1}",
                    task.Id, concurrentQueue.Count(x => x == task.Id));
            }

            Console.WriteLine("\nВсего в контейнере {0} элементов. ",
               concurrentQueue.Count);
            Console.ReadKey();
        }
开发者ID:Vladislav4380,项目名称:test_app,代码行数:13,代码来源:ConsoleOutputService.cs

示例13: ContainsRegex

        /// <summary>
        /// Finds all files in a given set of paths that contain the specified regex
        /// </summary>
        /// <param name="regex">The string to search for</param>
        /// <param name="ignoreCase">True to ignore case</param>
        /// <param name="paths">Paths to search</param>
        public static IEnumerable<string> ContainsRegex(this IFileService fileService, string regex, bool ignoreCase, params string[] paths)
        {
            RegexOptions options = RegexOptions.Compiled;
            if (ignoreCase) { options |= RegexOptions.IgnoreCase; }

            Regex r;
            try
            {
                r = new Regex(regex, options);
            }
            catch (ArgumentException exception)
            {
                // Bad regex
                throw new TaskArgumentException(exception.Message);
            }

            ConcurrentBag<string> matchingPaths = new ConcurrentBag<string>();

            Parallel.ForEach(paths, path =>
            {
                if (!fileService.FileExists(path)) { return; }

                Stream stream = fileService.CreateFileStream(path);
                using (StreamReader reader = new StreamReader(stream))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        if (r.IsMatch(line))
                        {
                            matchingPaths.Add(path);
                            break;
                        }
                    }
                }
            });

            return matchingPaths.OrderBy(s => s).ToList();
        }
开发者ID:JeremyKuhne,项目名称:XTask,代码行数:45,代码来源:Files.cs

示例14: Work

        private static async Task Work()
        {
            while (true)
            {
                using (var repository = new EFFeedRepository())
                {
                    var list = new ConcurrentBag<FeedItem>();
                    foreach (var source in Sources.SourcesDictionary)
                    {
                        var src = await repository.GetSourceAsync(source.Key);
                        var items = await source.Value.Work(src);

                        foreach (var item in items)
                        {
                            list.Add(item);
                            Debug.WriteLine(item.ItemId);
                        }
                    }
                    var sortedList = list.OrderBy(i => i.PublishDate);
                    await repository.AddOrUpdateRange(sortedList);
                }
                await Task.Delay(TimeSpan.FromMinutes(2));
            }
        }
开发者ID:Anarh2404,项目名称:TechNews,代码行数:24,代码来源:Program.cs

示例15: RunResearchPlanner

        private void RunResearchPlanner()
        {
            if (string.IsNullOrEmpty(this.empire.ResearchTopic))
            {
                //Added by McShooterz: random tech is less random, selects techs based on priority
                //Check for needs of empire
                        // Ship ship;
                        // int researchneeded = 0;

                        //if( ResourceManager.ShipsDict.TryGetValue(this.BestCombatShip, out ship))
                        //{
                        //    ship.shipData.TechScore / this.empire.Research
                        //}
                bool cybernetic = this.empire.data.Traits.Cybernetic > 0;
                bool atWar = false;
                bool highTaxes = false;
                bool lowResearch = false;
                bool lowincome = false;
                if (this.empire.GetRelations().Where(war => !war.Key.isFaction && ( war.Value.AtWar || war.Value.PreparingForWar)).Count() > 0)
                    atWar = true;
                if (this.empire.data.TaxRate >= .50f )
                    highTaxes = true;
                if (this.empire.GetPlanets().Sum(research => research.NetResearchPerTurn) < this.empire.GetPlanets().Count / 3)
                    lowResearch = true;
                int economics = 10-(int)(this.empire.Money / (this.empire.GrossTaxes +1));
                    //(int)(this.empire.data.TaxRate * 10 + this.empire.Money < this.empire.GrossTaxes?5:0);
                int needsFood =0;
                foreach(Planet hunger in this.empire.GetPlanets())
                {
                    if (cybernetic ? hunger.ProductionHere <1 : hunger.FoodHere <1)
                        needsFood++;

                }

                needsFood = needsFood>0 ? needsFood /this.empire.GetPlanets().Count :0;
                needsFood *= 10;
                //float moneyNeeded = this.empire.canBuildFrigates ? 25 : 0;
                //moneyNeeded = this.empire.canBuildCruisers ? 50 : moneyNeeded;
                //moneyNeeded = this.empire.canBuildCapitals ? 100 : moneyNeeded;
                //float money = this.empire.EstimateIncomeAtTaxRate(.5f) + this.empire.GetTotalShipMaintenance();
                //if (money < moneyNeeded)
                //{
                //    lowincome = true;
                //}
                switch (this.res_strat)
                {
                    case GSAI.ResearchStrategy.Random:
                    {

                        if (true)
                        {
                            Dictionary<string, int> priority = new Dictionary<string, int>();

                            priority.Add("SHIPTECH", HelperFunctions.GetRandomIndex(this.empire.getResStrat().MilitaryPriority + 4+ (atWar ? 6 : 2)));

                            priority.Add("Research", HelperFunctions.GetRandomIndex(this.empire.getResStrat().ResearchPriority +4+ (lowResearch ? 4 : 0)));
                            priority.Add("Colonization", HelperFunctions.GetRandomIndex(this.empire.getResStrat().ExpansionPriority + 4 +(!cybernetic?needsFood:0)));
                            priority.Add("Economic", HelperFunctions.GetRandomIndex(this.empire.getResStrat().ExpansionPriority +4+ (economics) ));
                            priority.Add("Industry", HelperFunctions.GetRandomIndex(this.empire.getResStrat().IndustryPriority + 4+ (cybernetic?needsFood:0)));
                            priority.Add("General", HelperFunctions.GetRandomIndex(4));
                            priority.Add("GroundCombat", HelperFunctions.GetRandomIndex(this.empire.getResStrat().MilitaryPriority +4+ (atWar ? 4 : 0)));

                            string sendToScript = "";
                            int max = 0;
                            foreach (KeyValuePair<string, int> pWeighted in priority.OrderByDescending(pri => pri.Value))
                            {
                                if (max > 3)
                                    break;
                                if (pWeighted.Value < 3 && !string.IsNullOrEmpty(sendToScript))
                                    continue;
                                //if (!string.IsNullOrEmpty(sendToScript))
                                sendToScript += ":";
                                if (pWeighted.Key == "SHIPTECH")
                                {
                                    sendToScript += "ShipWeapons:ShipDefense:ShipGeneral:ShipHull";
                                    max += 4;

                                }
                                else
                                {
                                    sendToScript += pWeighted.Key;
                                    max++;
                                }

                            }
                            if (ScriptedResearch("CHEAPEST", "TECH", "TECH"+sendToScript))
                                return;

                        }

                        //changed by gremlin exclude module tech that we dont have any ships that use it.
                        ConcurrentBag<Technology> AvailableTechs = new ConcurrentBag<Technology>();
                        //foreach (KeyValuePair<string, Ship_Game.Technology> Technology in ResourceManager.TechTree)

                        Parallel.ForEach(ResourceManager.TechTree, Technology =>
                        {
                            TechEntry tech = null;// new TechEntry();
                            bool techexists = this.empire.GetTDict().TryGetValue(Technology.Key, out tech);
                            if (!techexists || tech == null)
                                //continue;
//.........这里部分代码省略.........
开发者ID:castroev,项目名称:StardriveBlackBox-verRadicalElements-,代码行数:101,代码来源:GSAI.cs


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