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


C# Queue.Where方法代码示例

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


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

示例1: InitializePrimes

 private static int[] InitializePrimes(int limit)
 {
     var candidates = new Queue<int>(Enumerable.Range(2, limit - 1));
     var primes = new List<int>();
     do
     {
         var prime = candidates.Dequeue();
         primes.Add(prime);
         candidates = new Queue<int>(candidates.Where(x => x % prime != 0));
     } while (candidates.Any());
     return primes.ToArray();
 }
开发者ID:brandonscott,项目名称:xcsharp,代码行数:12,代码来源:Example.cs

示例2: UpdateMomentumMotion

    private IEnumerator UpdateMomentumMotion()
    {
        Queue<TimedValue> speedQueue = new Queue<TimedValue> ();

        while (true) {
            moSpeed.isOnGround = Physics.Linecast(compTrans.position, compTrans.position + Vector3.down);

            float speed = moSpeed.isOnGround ? engine.curSpeed : speedQueue.LastOrDefault().value;

            speedQueue.Enqueue(new TimedValue() { value = speed, time = Time.time} );
            if (speedQueue.Count > momentumParams.queueNums) {
                speedQueue.Dequeue();
            }

            List<float> recentSpeeds = speedQueue
                .Where(s => Time.time - s.time < momentumParams.queueTime)
                .Select(s => s.value).ToList();
            float avg = recentSpeeds.Aggregate(0f, (m, s) => m = m + s / recentSpeeds.Count);

            moSpeed.speed = avg;

            yield return null;
        }
    }
开发者ID:n0mimono,项目名称:my-motorbike,代码行数:24,代码来源:Motorbike.cs

示例3: CalculateMFI

        // Money Flow Index
        public static void CalculateMFI(out string key, StockPoints data, Dictionary<DateTime, Dictionary<string, double>> indicators, int period, out int offset)
        {
            key = string.Format("MFI({0})", period.ToString("00"));
            offset = period;

            // Typical Price = (High + Low + Close)/3
            double typicalPrice;

            // Raw Money Flow = Typical Price x Volume
            double rawMoneyFlow;

            // Money Flow Ratio = (x-period Positive Money Flow)/(x-period Negative Money Flow)
            double moneyFlowRatio;

            // Money Flow Index = 100 - 100/(1 + Money Flow Ratio)
            double moneyFlowIndex;

            double positiveMoneyFlow = 0D;
            double negativeMoneyFLow = 0D;

            Queue<double> moneyFlow = new Queue<double>();
            double previousTipycalPrice = (data[0].Low + data[0].High + data[0].Close) / 3;

            int i = 0;
            foreach (StockPoint point in data.Skip(1))
            {
                typicalPrice = (point.Low + point.High + point.Close) / 3;
                rawMoneyFlow = typicalPrice * point.Volume;
                moneyFlow.Enqueue(rawMoneyFlow * (typicalPrice >= previousTipycalPrice ? 1 : -1));

                if(moneyFlow.Count > period)
                {
                    moneyFlow.Dequeue();
                }

                if (i < period - 1)
                {
                    i++;
                }
                else
                {
                    positiveMoneyFlow = moneyFlow.Where(v => v >= 0).Sum();
                    negativeMoneyFLow = Math.Abs(moneyFlow.Where(v => v < 0).Sum());

                    moneyFlowRatio = positiveMoneyFlow / negativeMoneyFLow;
                    moneyFlowIndex = 100 - (100 / (1 + moneyFlowRatio));

                    AddValue(point.PointDateTime, key, moneyFlowIndex, indicators);
                }

                previousTipycalPrice = typicalPrice;
            }
        }
开发者ID:Kushagratrivedi,项目名称:GitHub,代码行数:54,代码来源:IndicatorLib.cs

示例4: EnqueueFileList

 private void EnqueueFileList(List<RequireFile> fileList, Queue<string> queue, List<string> files)
 {
     foreach (var file in files)
     {
         if (!fileList.Where(r => r.Name.ToLower() == file.ToLower()).Any()
             && !queue.Where(r => r.ToLower() == file.ToLower()).Any())
         {
             queue.Enqueue(file);
         }
     }
 }
开发者ID:vulh91,项目名称:RequireJSDotNet,代码行数:11,代码来源:AutoBundleConfigProcessor.cs

示例5: smoothInput

        private static Point smoothInput(Point current, Queue<Point> recent, int distance)
        {
            if (recent.Count == recentCount)
                recent.Dequeue();

            recent.Enqueue(current);

            Point avg = new Point();

            var near = recent.Where(point =>
                Math.Sqrt(Math.Pow(point.X - current.X, 2) + Math.Pow(point.Y - current.Y, 2)) < distance);

            avg.X = near.Sum(point => point.X) / near.Count();
            avg.Y = near.Sum(point => point.Y) / near.Count();

            return avg;
        }
开发者ID:solson,项目名称:DSAE,代码行数:17,代码来源:Form1.cs

示例6: enqueueNewFiles

 private void enqueueNewFiles(IEnumerable<string> files, Queue<string> pendingQueue, List<RequireFile> processedFiles)
 {
     foreach (var file in files)
     {
         if (!processedFiles.Where(r => r.Name.ToLower() == file.ToLower()).Any()
             && !pendingQueue.Where(r => r.ToLower() == file.ToLower()).Any())
         {
             pendingQueue.Enqueue(file);
         }
     }
 }
开发者ID:vtfuture,项目名称:RequireJSDotNet,代码行数:11,代码来源:AutoBundleConfigProcessor.cs

示例7: CheckForNewAds

        protected List<Ad> CheckForNewAds(Action<CheckForNewAdsState> stateChangedCallback, Action<List<Ad>> completedCallback, CancellationToken cancelationToken)
        {
            var state = new CheckForNewAdsState();
            var result = new List<Ad>();
            int totalProcessed = 0;

            int maxAds = Managers.SettingsManager.GetSettings().CheckForNewAdsMaxAdsCount;
            int frameSize = 100;
            int minAds = 200;
            double minNewAdsInFrame = 0.1;

            foreach (var connector in Managers.ConnectorsManager.GetConnectors())
            {
                Managers.LogEntriesManager.AddItem(SeverityLevel.Information, string.Format("Starting download from {0}.", connector.Id));
                int adsCount = 0;

                List<Ad> connectorResult = new List<Ad>();
                List<Ad> lastAds = Repositories.AdsRepository.GetLastAds(connector.Id, maxAds);
                Ad lastAd = lastAds.FirstOrDefault();
                DateTime lastCollectionDate = lastAd == null ? DateTime.Now.Date : lastAd.CollectDate.Date;

                Queue<bool> frame = new Queue<bool>(frameSize);/*true for new or republished ad, otherwise false*/

                try
                {
                    foreach (var ad in connector.GetAds())
                    {
                        adsCount++;
                        totalProcessed++;
                        var isNewAd = IsNewOrRepublishedAd(ad, lastAds);

                        state.Progress = totalProcessed;
                        state.SourceUrl = connector.Id;
                        state.Canceled = cancelationToken.IsCancellationRequested;
                        state.Description = "Processing...";
                        stateChangedCallback(state);

                        connectorResult.Add(ad);
                        frame.Enqueue(isNewAd);
                        if (frame.Count > frameSize)
                        {
                            frame.Dequeue();
                        }

                        if ((adsCount > minAds && frame.Count == frameSize && ((double)frame.Where(item => item).Count()/(double)frameSize) < minNewAdsInFrame) ||
                            adsCount >= maxAds || cancelationToken.IsCancellationRequested)
                        {
                            break;
                        }
                    }

                    ProcessCollectDate(connectorResult, DateTime.Now);

                    state.Description = "Analyzing...";
                    stateChangedCallback(state);

                    var acceptance = AddNewOrCreateHistory(connectorResult);
                    Managers.LogEntriesManager.AddItem(SeverityLevel.Information,
                        string.Format("{0} Collection from {1} finished. Processed: {2}; New ads: {3}; Added to History: {4}; Rejected: {5};",
                        this.GetType().Name, connector.Id,
                        acceptance.Count(),
                        acceptance.Where(a => a == AdAcceptance.Accepted).Count(),
                        acceptance.Where(a => a == AdAcceptance.History).Count(),
                        acceptance.Where(a => a == AdAcceptance.Rejected).Count()));

                    result.AddRange(connectorResult);
                }
                catch (Exception ex)
                {
                    Managers.LogEntriesManager.AddItem(SeverityLevel.Error,
                        string.Format("{0} Download error. {1}", this.GetType().Name, ex.Message), ex.StackTrace);
                }

                if (cancelationToken.IsCancellationRequested)
                {
                    break;
                }
            }

            completedCallback(result);
            return result;
        }
开发者ID:kuzminyv,项目名称:ad-collector,代码行数:82,代码来源:AdsManager.cs

示例8: PlayField

 public string PlayField(Queue<Player> players)
 {
     string field = "";
     Player player;
     for (int bit = 1; bit < 512; bit <<= 1) {
         player = players.Where (p => (bit & p.Moves) != 0).FirstOrDefault ();
         field += player != null ? player.Sign.ToString () : " ";
     }
     return field;
 }
开发者ID:olafbauer,项目名称:TicTacToe,代码行数:10,代码来源:Game.cs

示例9: _02_02_CollectionsGenerischTest


//.........这里部分代码省略.........
            {
                Debug.WriteLine("preis: " + actNode.Value);

            }

            // Iterieren über die LinkedList rückwärts
            for (actNode = AktuellePreise.Last; actNode != null; actNode = actNode.Previous)
            {
                Debug.WriteLine("preis: " + actNode.Value);

            }

            foreach (var p in AktuellePreise)
            {
                // Current greift auf Value vom Node zu
                Debug.WriteLine("preis: " + p);
            }


            // 2 PReise entfernen
            Preisliste.Remove(new Preis(12, 45));

            // den 3. Preis entfernen
            Preisliste.RemoveAt(3);

            
            AktuellePreise.Clear();
            foreach (var p in Preisliste)
            {
                AktuellePreise.AddLast(p.ToString());
            }

            // Telefonbuch
            var telBuch = new Dictionary<string, int>();

            telBuch.Add("Anton", 4711);

            // neuer Eintrag hinzugefügt, da noch nicht unter dem Schlüssel vorhanden
            // Folgeder Indexeraufruf entspricht telbuch.Add("Berta", 6969);
            telBuch["Berta"] = 6969;

            // Eintrag geändert
            telBuch["Berta"] = 7766;

            telBuch["Cäsar"] = 3344;

            // Iterieren durch Dictionary 1
            var telBuchListe = new LinkedList<string>();
            foreach (var k in telBuch.Keys)
            {
                telBuchListe.AddLast(k + ": " + telBuch[k]);
            }

            // Iterieren durch Dictionary 2
            telBuchListe.Clear();
            foreach (KeyValuePair<string, int> pair in telBuch)
            {
                telBuchListe.AddLast(pair.Key + ": " + pair.Value);
            }

            // Queue

            var Warteschlange = new Queue<Tuple<int, string>>();


            // Aufträge in Warteschlange einstellen
            Warteschlange.Enqueue(new Tuple<int, string>(99, "Abwaschen"));
            Warteschlange.Enqueue(new Tuple<int, string>(77, "Abtrocknen"));
            Warteschlange.Enqueue(new Tuple<int, string>(66, "Wegräumen"));

            // Jobverarbeitung schaltet sich ein
            var Auftragsprotokoll = new LinkedList<string>();
            var Auftrag = Warteschlange.Dequeue();
            Auftragsprotokoll.AddLast("Führe aus: " + Auftrag.Item2);

            Warteschlange.Enqueue(new Tuple<int, string>(55, "Zumachen"));

            // Nachschauen, ohne zu entnehmen
            var erstes = Warteschlange.Peek();

            // Da die Queue IEnumerable implementiert, können alle aktuellen
            // Einträge mittels foreach- Schleife besucht werden
            foreach (var job in Warteschlange)
            {
                Debug.WriteLine(job.Item2);
            }

            var alleJobsDieMitABeginnen = Warteschlange.Where(r => r.Item2.StartsWith("A")).ToArray();

            Auftrag = Warteschlange.Dequeue();
            Auftragsprotokoll.AddLast("Führe aus: " + Auftrag.Item2);

            // Alle restlichen verarbeiten
            while (Warteschlange.Count > 0)
            {
                Auftrag = Warteschlange.Dequeue();
                Auftragsprotokoll.AddLast("Führe aus: " + Auftrag.Item2);
            }

        }
开发者ID:mk-prg-net,项目名称:CSharp45.Basics,代码行数:101,代码来源:_02_02_CollectionsTests.cs

示例10: GetResponse

        /// <summary>
        /// 用Socket取得遠端列表的(全部/任一)回應
        /// </summary>
        /// <param name="remoteIpList">遠端目的列表</param>
        /// <param name="request">request data</param>
        /// <param name="response">response data</param>
        /// <param name="waitAll">是否等待所有遠端response</param>
        /// <param name="sendTimeout">default: 3 second</param>
        /// <param name="receiveTimeout">default: 3 second</param>
        /// <returns>true:取得response/false:遠端連線異常</returns>
        protected virtual bool GetResponse(IList<IPEndPoint> remoteIpList, byte[] request, out byte[] response,bool waitAll = false, int sendTimeout = 3000, int receiveTimeout = 30000)
        {
            Queue<Task<byte[]>> resultList = new Queue<Task<byte[]>>();
            response = null;
            try
            {
                foreach (IPEndPoint dest in remoteIpList)
                {
                    //task run
                    Task<byte[]> task = Task.Run(() => { return GetResponse(dest, request, sendTimeout, receiveTimeout); });
                    //push in task list
                    resultList.Enqueue(task);
                }
                if (waitAll)
                {
                    bool complete = Task.WaitAll(resultList.ToArray(), 50000);//timeout: 50 second
                    //if need compare all result to do that// if need TODO...
                    //resultList.GroupBy(n => n.Result)....;

                    //if complete filter result is null and get the first task result
                    response = complete ? resultList.Where(n => n.Result != null).FirstOrDefault().Result : null;
                    return complete;

                }
                else
                {
                    int index = Task.WaitAny(resultList.ToArray(), 50000);//tiemout: 50 second
                    //if anyone is complete use the return index to find task result
                    response = index.Equals(-1) ? null : resultList.ElementAtOrDefault(index).Result;
                    return !index.Equals(-1);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("[GetResponse]Error:" + ex.Message + Environment.NewLine + ex.StackTrace);
                return false;
            }
        }
开发者ID:knarf7112,项目名称:SocketServer,代码行数:48,代码来源:SocketProxy.cs

示例11: RemovePlayer

        internal void RemovePlayer(string nick)
        {
            var before = players.Where(p => p.State != PlayerState.PausedPlaying).Count();

            players = new Queue<PokerPlayer>(players.Where(p => p.Nick != nick));

            var after = players.Where(p => p.State != PlayerState.PausedPlaying).Count();

            if (before == 2 && after == 1)
            {
                //Game must end, not enough players
                ResetGame();
            }
        }
开发者ID:Avatarchik,项目名称:huffelpuff-irc-bot,代码行数:14,代码来源:PokerGame.cs

示例12: Pars

        public bool Pars(string modelPath)
        {
            StreamReader sr = new StreamReader(modelPath);
            string data = sr.ReadToEnd();
            sr.Close();

            MessageParser.NET.Tools.XmlParser xml = new MessageParser.NET.Tools.XmlParser();

            string ConceptualSection = xml.GetSubTreeByParent(data, "edmx:StorageModels")[0].InnerXml;
            var dic = GetsRoles(ConceptualSection);

            var matchesEntityType = xml.GetSubTreeByParent(ConceptualSection, "EntityType");

            var entityTypeList = xml.GetSubTreeByParent(ConceptualSection, "EntityType");
            var associationList = xml.GetSubTreeByParent(ConceptualSection, "Association");

            Queue<struc> result = new Queue<struc>();
            Queue<AssociationStruct> associationResult = new Queue<AssociationStruct>();

            for (int k = 0; k < associationList.Length; k++)
            {
                associationResult.Enqueue(GetAssociation(associationList[k].OuterXml));
            }

            for (int k = 0; k < entityTypeList.Length; k++)
            {
                {
                    struc te = new struc();
                    te.Fname = Filter(xml.GetAttributeValue(entityTypeList[k].OuterXml, "EntityType", "Name"));

                    te.Props = GetProperty(entityTypeList[k].OuterXml);

                    te.Map = GetMapForTable(xml.GetSubTreeByParent(data, "edmx:Mappings")[0].InnerXml,te.Fname);

                    if (result.Where(p => p.Fname == te.Fname).FirstOrDefault() != null)
                        continue;

                    if (!string.IsNullOrEmpty(NameSpace))
                        te.NameSpace = NameSpace;

                    te.ModelName = te.Map.Name;
                    te.TableName = te.Map.StoreEntitySet;
                    te.Fname = "frm" + te.Map.Name;

                    result.Enqueue(te);
                }
            }

            var filter = Distinct(result.ToArray());
            ParsedData = filter;
            ProcessAssociation(filter, associationResult.ToArray());

            Translate(filter, dic);

            FormGenerator generate = new FormGenerator();
            var designFile = generate.GenerateFormDesign(filter);

            foreach (struc t in designFile)
            {
                if (File.Exists(OutPutAddress + "\\" + t.Fname + ".Designer.cs"))
                    File.Delete(OutPutAddress + "\\" + t.Fname + ".Designer.cs");

                StreamWriter sw = new StreamWriter(OutPutAddress + "\\" + t.Fname + ".Designer.cs", true);
                sw.Write(t.Design);
                sw.Close();

            }

            var efName = regexPatterns.GetMatches(regexPatterns.GetMatch(data, regexPatterns.EntitiyName).Value, regexPatterns.GetValue)[0].Value.Replace('"', ' ').Trim();

            CodeGenerator code = new CodeGenerator();
            var codeFile = code.GenerateClass(filter, efName);

            foreach (struc t in codeFile)
            {
                if (File.Exists(OutPutAddress + "\\" + t.Fname + ".cs"))
                    File.Delete(OutPutAddress + "\\" + t.Fname + ".cs");

                StreamWriter sw = new StreamWriter(OutPutAddress + "\\" + t.Fname + ".cs", true);
                sw.Write(t.Code);
                sw.Close();

            }

            for (int i = 0; i < result.Count; i++)
            {
                if (File.Exists(OutPutAddress + "\\" + result.ElementAt(i).Fname + ".resx"))
                    File.Delete(OutPutAddress + "\\" + result.ElementAt(i).Fname + ".resx");

                File.Copy(Environment.CurrentDirectory + "\\RFile.resx", OutPutAddress + "\\" + result.ElementAt(i).Fname + ".resx");
            }

            return true;
        }
开发者ID:AlirezaP,项目名称:WinFormScaffolding.Net,代码行数:94,代码来源:Scaffolding.cs

示例13: Distinct

 private struc[] Distinct(struc[] input)
 {
     Queue<struc> res = new Queue<struc>();
     for (int i = 0; i < input.Length; i++)
     {
         if (res.Where(p => p.Fname == input[i].Fname).FirstOrDefault() == null)
             res.Enqueue(input[i]);
     }
     return res.ToArray();
 }
开发者ID:AlirezaP,项目名称:WinFormScaffolding.Net,代码行数:10,代码来源:Scaffolding.cs


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