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


C# IEnumerable.ElementAtOrDefault方法代码示例

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


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

示例1: SetDeviceValue

        public SetDeviceValue(IDeviceRepository deviceRepository, IEnumerable<string> parameters)
        {
            mDeviceRepository = deviceRepository;

            mDeviceToSet = parameters.ElementAtOrDefault(0);
            mValueToSet = parameters.ElementAtOrDefault(1);
        }
开发者ID:markyme,项目名称:DH,代码行数:7,代码来源:SetDeviceValue.cs

示例2: BotAddCommand

        public void BotAddCommand(CommandContext context, IEnumerable<string> arguments)
        {
            if (arguments.Count() < 1)
            {
                SendInContext(context, "Usage: !bot add name [nick [arguments]]");
                return;
            }

            string botID = arguments.ElementAt(0);
            if (!GameManager.Bots.ContainsKey(botID))
            {
                SendInContext(context, "Invalid bot!");
                return;
            }

            string botNick = arguments.ElementAtOrDefault(1) ?? botID;

            try
            {
                Manager.AddBot(botNick, (IBot)GameManager.Bots[botID].GetConstructor(new Type[] { typeof(GameManager), typeof(IEnumerable<string>) }).Invoke(new object[] { Manager, arguments.Skip(2) }));
                Manager.SendPublic(context.Nick, "Added <{0}> (a bot of type {1})", botNick, botID);
            }
            catch (ArgumentException e)
            {
                SendInContext(context, "Error adding {0}: {1}", botNick, e.Message);
            }
        }
开发者ID:puckipedia,项目名称:CardsAgainstIRC,代码行数:27,代码来源:Base.cs

示例3: Login

 public Login(IUserRepository userRepository, ILoginActions loginActions, IEnumerable<string> parameters)
 {
     mUserRepository = userRepository;
     mLoginActions = loginActions;
     mParameters = parameters;
     mUserToLogin = mParameters.ElementAtOrDefault(0);
 }
开发者ID:markyme,项目名称:DH,代码行数:7,代码来源:Login.cs

示例4: GetString

        private static string GetString(this IEnumerable<Cell> source, string location, IEnumerable<string> strings) {
            var cell = source.FirstOrDefault(x => x.Location == location);
            if (string.IsNullOrEmpty(cell?.Node.Value)) return null;

            var id = cell.Node.Value.AsInt();
            return strings.ElementAtOrDefault(id);
        }
开发者ID:gro-ove,项目名称:actools,代码行数:7,代码来源:SharedLocaleReader.cs

示例5: Normalize

        public static IEnumerable<Token> Normalize(
            IEnumerable<Token> tokens, Func<string, bool> nameLookup)
        {
            var indexes =
                from i in
                    tokens.Select(
                        (t, i) =>
                        {
                            var prev = tokens.ElementAtOrDefault(i - 1).ToMaybe();
                            return t.IsValue() && ((Value)t).ExplicitlyAssigned
                                   && prev.MapValueOrDefault(p => p.IsName() && !nameLookup(p.Text), false)
                                ? Maybe.Just(i)
                                : Maybe.Nothing<int>();
                        }).Where(i => i.IsJust())
                select i.FromJustOrFail();

            var toExclude =
                from t in
                    tokens.Select((t, i) => indexes.Contains(i) ? Maybe.Just(t) : Maybe.Nothing<Token>())
                        .Where(t => t.IsJust())
                select t.FromJustOrFail();

            var normalized = tokens.Except(toExclude);

            return normalized;
        }
开发者ID:Thilas,项目名称:commandline,代码行数:26,代码来源:Tokenizer.cs

示例6: CreateInlineDiffs

        private void CreateInlineDiffs(IEnumerable<ILine> originals, IEnumerable<ILine> modifieds)
        {
            if (originals.Count() != modifieds.Count())
            {
                originalLines.AddRange(
                    originals.Select(x => new ModificationLine(new[] { new Span(x.Value, SpanKind.Deletion) }))
                );
                modifiedLines.AddRange(
                    modifieds.Select(x => new ModificationLine(new[] { new Span(x.Value, SpanKind.Addition) }))
                );
                return;
            }

            var maxLines = Math.Max(originals.Count(), modifieds.Count());

            for (var i = 0; i < maxLines; i++)
            {
                var originalLine = originals.ElementAtOrDefault(i);
                var modifiedLine = modifieds.ElementAtOrDefault(i);

                if (originalLine == null && modifiedLine == null)
                    continue;
                if (originalLine != null && modifiedLine == null)
                    originalLines.Add(new ModificationLine(new[] { new Span(originalLine.Value, SpanKind.Deletion) }));
                else if (originalLine == null)
                    modifiedLines.Add(new ModificationLine(new[] { new Span(modifiedLine.Value, SpanKind.Addition) }));
                else
                {
                    var originalToModifiedChanges = DiffInline(originalLine, modifiedLine);

                    originalLines.Add(new ModificationLine(new[] { new Span(originalLine.Value, SpanKind.Equal) }));
                    modifiedLines.Add(new ModificationLine(originalToModifiedChanges));
                }
            }
        }
开发者ID:jagregory,项目名称:sharpdiff,代码行数:35,代码来源:ModificationSnippet.cs

示例7: TryGet

 IHdumNode TryGet(IHdumNode caller, IEnumerable<IHdumNode> parameters)
 {
     var key = parameters.First().As<IHdumContent<String>>().Content;
     if (caller.HasMember(key))
         return caller[key];
     else
         return parameters.ElementAtOrDefault(1);
 }
开发者ID:Alphish,项目名称:hdum-cs,代码行数:8,代码来源:HdumEntityMethodsProvider.cs

示例8: OnActionsCleared

 private void OnActionsCleared(Pawn source, IEnumerable<PawnAction> actionsCleared)
 {
     for (int i = _currentStep; i > 0; i--) {
         PawnAction action = actionsCleared.ElementAtOrDefault(i);
         if (action != null) {
             action.Undo();
         }
     }
 }
开发者ID:RolandMQuiros,项目名称:Lost-Generation,代码行数:9,代码来源:Timeline.cs

示例9: ATR

        /// <summary>
        /// Calculates Average True Range indicator
        /// </summary>
        /// <param name="highs">Signal representing price highs</param>
        /// <param name="lows">Signal representing price lows</param>
        /// <param name="closes">Signal representing closing prices</param>
        /// <param name="periods">Number of periods</param>
        /// <returns>Object containing operation results</returns>
        public static ATRResult ATR(IEnumerable<double> highs, IEnumerable<double> lows, IEnumerable<double> closes, int periods)
        {
            // calculate True Range first
            var trueRangeList = new List<double>();
            
            for (int i = 0; i < highs.Count(); i++)
            {
                double currentHigh = highs.ElementAt(i);
                double currentLow = lows.ElementAt(i);
                double previousClose = closes.ElementAtOrDefault(i - 1);

                double highMinusLow = currentHigh - currentLow;
                double highMinusPrevClose = i != 0 ? Math.Abs(currentHigh - previousClose) : 0;
                double lowMinusPrevClose = i != 0 ? Math.Abs(currentLow - previousClose) : 0;

                double trueRangeValue = highMinusLow;

                if (highMinusPrevClose > trueRangeValue)
                {
                    trueRangeValue = highMinusPrevClose;
                }
                if (lowMinusPrevClose > trueRangeValue)
                {
                    trueRangeValue = lowMinusPrevClose;
                }

                trueRangeList.Add(trueRangeValue);
            }

            // calculate Average True Range
            var atrList = new List<double>();

            double initialATR = trueRangeList.Take(periods).Average();
            atrList.Add(initialATR);

            for (int i = periods; i < trueRangeList.Count; i++)
            {
                double currentATR = (atrList[i - periods] * (periods - 1) + trueRangeList[i]) / periods;
                atrList.Add(currentATR);
            }

            var result = new ATRResult()
            {
                StartIndexOffset = periods - 1,
                Values = atrList
            };

            return result;
        }
开发者ID:conradakunga,项目名称:QuantTrading,代码行数:57,代码来源:ATR.cs

示例10: PreprocessLines

        private IEnumerable<ScenarioLine> PreprocessLines(IEnumerable<ScenarioLine> lines, IEnumerable<string> fieldNames,
                                                    IEnumerable<string> example)
        {
            foreach (var line in lines)
            {
                var processed = line.Text;

                for (var fieldIndex = 0; fieldIndex < fieldNames.ToArray().Length; fieldIndex++)
                {
                    var name = fieldNames.ToArray()[fieldIndex];
                    processed = processed.Replace("<" + name + ">", example.ElementAtOrDefault(fieldIndex));
                }
                yield return new ScenarioLine {Text = processed, LineNumber = line.LineNumber};
            }
        }
开发者ID:codereflection,项目名称:storevil,代码行数:15,代码来源:ScenarioPreprocessor.cs

示例11: GetAbilityScores

        /// <summary>
        /// Gets the ability scores from the program argumentlist by index. If the element is missing 
        /// a default value is used
        /// </summary>
        private static Dictionary<AbilityType, int> GetAbilityScores(IEnumerable<string> abilities)
        {
            const string defaultScore = "11";
            var str = Int32.Parse(abilities.ElementAtOrDefault(0) ?? defaultScore);
            var dex = Int32.Parse(abilities.ElementAtOrDefault(1) ?? defaultScore);
            var con = Int32.Parse(abilities.ElementAtOrDefault(2) ?? defaultScore);
            var intel = Int32.Parse(abilities.ElementAtOrDefault(3) ?? defaultScore);
            var wis = Int32.Parse(abilities.ElementAtOrDefault(4) ?? defaultScore);
            var cha = Int32.Parse(abilities.ElementAtOrDefault(5) ?? defaultScore);

            var abilityScores = new Dictionary<AbilityType, int>() {
                {AbilityType.Strength, str},
                {AbilityType.Dexterity, dex},
                {AbilityType.Constitution, con},
                {AbilityType.Intelligence, intel},
                {AbilityType.Wisdom, wis},
                {AbilityType.Charisma, cha}
            };
            return abilityScores;
        }
开发者ID:RogaDanar,项目名称:Dnd,代码行数:24,代码来源:Program.cs

示例12: RemoveInitializedDeclarationAndReturnPattern

            public IEnumerable<StatementSyntax> RemoveInitializedDeclarationAndReturnPattern(IEnumerable<StatementSyntax> statements)
            {
                // if we have inline temp variable as service, we could just use that service here.
                // since it is not a service right now, do very simple clean up
                if (statements.ElementAtOrDefault(2) != null)
                {
                    return statements;
                }

                var declaration = statements.ElementAtOrDefault(0) as LocalDeclarationStatementSyntax;
                var returnStatement = statements.ElementAtOrDefault(1) as ReturnStatementSyntax;
                if (declaration == null || returnStatement == null)
                {
                    return statements;
                }

                if (declaration.Declaration == null ||
                    declaration.Declaration.Variables.Count != 1 ||
                    declaration.Declaration.Variables[0].Initializer == null ||
                    declaration.Declaration.Variables[0].Initializer.Value == null ||
                    declaration.Declaration.Variables[0].Initializer.Value is StackAllocArrayCreationExpressionSyntax ||
                    returnStatement.Expression == null)
                {
                    return statements;
                }

                if (!ContainsOnlyWhitespaceTrivia(declaration) ||
                    !ContainsOnlyWhitespaceTrivia(returnStatement))
                {
                    return statements;
                }

                var variableName = declaration.Declaration.Variables[0].Identifier.ToString();
                if (returnStatement.Expression.ToString() != variableName)
                {
                    return statements;
                }

                return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.ReturnStatement(declaration.Declaration.Variables[0].Initializer.Value));
            }
开发者ID:Rickinio,项目名称:roslyn,代码行数:40,代码来源:CSharpMethodExtractor.PostProcessor.cs

示例13: DataTuple

 public DataTuple(IEnumerable<string> items)
 {
     Label = items.ElementAtOrDefault(0) ?? "";
     Value = items.ElementAtOrDefault(1) ?? "";
     Unit = items.ElementAtOrDefault(2) ?? "";
 }
开发者ID:rrhartjr,项目名称:Demo.Report,代码行数:6,代码来源:DataTuple.cs

示例14: Compile

        public override CompileResult Compile(IEnumerable<Expression> children, ParsingContext context)
        {
            // 2 is allowed, Excel returns FALSE if false is the outcome of the expression
            if(children.Count() < 2) throw new ExcelErrorValueException(eErrorType.Value);
            var args = new List<FunctionArgument>();
            Function.BeforeInvoke(context);
            var firstChild = children.ElementAt(0);
            var v = firstChild.Compile().Result;

            /****  Handle names and ranges ****/
            if (v is ExcelDataProvider.INameInfo)
            {
                v = ((ExcelDataProvider.INameInfo)v).Value;
            }

            if (v is ExcelDataProvider.IRangeInfo)
            {
                var r=((ExcelDataProvider.IRangeInfo)v);
                if(r.GetNCells()>1)
                {
                    throw(new ArgumentException("Logical can't be more than one cell"));
                }
                v = r.GetOffset(0, 0);
            }
            bool boolVal;
            if(v is bool)
            {
                boolVal = (bool)v;
            }
            else if(!Utils.ConvertUtil.TryParseBooleanString(v, out boolVal))
            {
                if(OfficeOpenXml.Utils.ConvertUtil.IsNumeric(v))
                {
                    boolVal = OfficeOpenXml.Utils.ConvertUtil.GetValueDouble(v)!=0;
                }
                else
                {
                    throw (new ArgumentException("Invalid logical test"));
                }
            }
            /****  End Handle names and ranges ****/

            args.Add(new FunctionArgument(boolVal));
            if (boolVal)
            {
                var val = children.ElementAt(1).Compile().Result;
                args.Add(new FunctionArgument(val));
                args.Add(new FunctionArgument(null));
            }
            else
            {
                object val;
                var child = children.ElementAtOrDefault(2);
                if (child == null)
                {
                    // if no false expression given, Excel returns false
                    val = false;
                }
                else
                {
                    val = child.Compile().Result;
                }
                args.Add(new FunctionArgument(null));
                args.Add(new FunctionArgument(val));
            }
            return Function.Execute(args, context);
        }
开发者ID:princeoffoods,项目名称:EPPlus,代码行数:67,代码来源:IfFunctionCompiler.cs

示例15: createNewDefaultUniqueValueRenderer

 private static UniqueValueRenderer createNewDefaultUniqueValueRenderer(GraphicsLayer graphicsLayer, IEnumerable<object> uniqueValues, FieldInfo attributeField, LinearGradientBrush defaultColorRampGradientBrush, IEnumerable<Symbol> existingSymbolSet)
 {
     Symbol defaultSymbol = graphicsLayer.GetDefaultSymbol();
     UniqueValueRenderer uniqueValueRenderer = new UniqueValueRenderer()
     {
         Field = attributeField != null ? attributeField.Name : null,
         DefaultSymbol = defaultSymbol,
     };
     if (uniqueValues != null)
     {
         List<Symbol> symbols = new List<Symbol>();
         int i = 0;
         foreach (object uniqueValue in uniqueValues)
         {
             Symbol symbol = null;
             if (existingSymbolSet != null)
                 symbol = existingSymbolSet.ElementAtOrDefault(i);
             if (symbol == null)
                 symbol = graphicsLayer.GetDefaultSymbolClone();
             uniqueValueRenderer.Infos.Add(new UniqueValueInfoObj()
             {
                 Symbol = symbol,
                 SerializedValue = uniqueValue,
                 FieldType = attributeField.FieldType,
             });
             symbols.Add(symbol);
             i++;
         }
         if (defaultColorRampGradientBrush != null)
         {
             if (existingSymbolSet == null) // apply the gradient brush, only if symbols have not been pre-defined
             {
                 applyLinearGradientBrushToSymbolSet(symbols, defaultColorRampGradientBrush, defaultSymbol);
             }
         }
     }
     return uniqueValueRenderer;
 }
开发者ID:konglingjie,项目名称:arcgis-viewer-silverlight,代码行数:38,代码来源:LayerRendererHelper.cs


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