本文整理汇总了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);
}
示例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);
}
}
示例3: Login
public Login(IUserRepository userRepository, ILoginActions loginActions, IEnumerable<string> parameters)
{
mUserRepository = userRepository;
mLoginActions = loginActions;
mParameters = parameters;
mUserToLogin = mParameters.ElementAtOrDefault(0);
}
示例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);
}
示例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;
}
示例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));
}
}
}
示例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);
}
示例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();
}
}
}
示例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;
}
示例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};
}
}
示例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;
}
示例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));
}
示例13: DataTuple
public DataTuple(IEnumerable<string> items)
{
Label = items.ElementAtOrDefault(0) ?? "";
Value = items.ElementAtOrDefault(1) ?? "";
Unit = items.ElementAtOrDefault(2) ?? "";
}
示例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);
}
示例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;
}