protected PropertyExpression(object obj, IEnumerable<PropertyExpressionPart> parts) { if (obj == null) throw new ArgumentNullException("obj"); if (parts == null) throw new ArgumentNullException("parts"); /*foreach (object item in parts) { if (item == null) { throw new ArgumentException("An item inside the enumeration was null.", "parts"); } }*/ if (parts.Cast<object>().Any(item => item == null)) { throw new ArgumentException(Resources.AnItemWasNull, "parts"); } _parts = new List<PropertyExpressionPart>(parts); if (_parts.Count == 0) throw new ArgumentException(Resources.OnePartRequired, "parts"); _finalPart = _parts.Last(); //whenever the final part's value changes, that means the value of the expression as a whole has changed _finalPart.ValueChanged += delegate { OnValueChanged(); }; //assign the initial object in the potential chain of objects resolved by the expression parts _parts[0].Object = obj; }
public CollectionView(IEnumerable collection) { if (collection == null) { throw new ArgumentNullException("collection"); } this.sourceCollection = collection; if (collection.Cast<object>().Any()) { this.currentItem = collection.Cast<object>().First(); this.currentPosition = 0; } else { this.currentPosition = -1; this.IsCurrentAfterLast = this.IsCurrentBeforeFirst = true; } INotifyCollectionChanged incc = collection as INotifyCollectionChanged; if (incc != null) { incc.CollectionChanged += this.OnCollectionChanged; } }
public IDbCommandResult Convert(IEnumerable values) { if (values.IsEmpty()) { return new QueryResult(); } var type = values.GetTypeOfValues(); if (type.IsValueType || type == typeof(string)) { return QueryResultOfValues(values, type); } if (type == typeof(DynamicRecord)) { return QueryResultOfDynamicRecord(values.Cast<DynamicRecord>()); } if (type == typeof(DynamicDataRow)) { return QueryResultOfDynamicDataRow(values.Cast<DynamicDataRow>()); } if (type.IsAssignableFrom(typeof(IDictionary))) { return QueryResultOfDictionary((IEnumerable<IDictionary>)values); } return QueryResultOfType(values, type); }
private static IList SelectIndividualGlyphsOrPassBoxComposition(IEnumerable boxElements) { if (boxElements == null) return null; Contract.RequiresForAll(boxElements.Cast<object>(), element => element is IBoxElement); return boxElements.Cast<object>().VirtualSelectMany<object, BoxCompositionViewModel, GlyphRunViewModel, object>(bc => bc.ToSingleton(), glyphRun => glyphRun).ToList(); }
public static IColumn CreateColumn(Type dataType, IEnumerable<object> data) { if (new[]{typeof(Int64), typeof(Int32), typeof(Int16), typeof(UInt16), typeof(UInt32), typeof(UInt64), typeof(int)}.Contains(dataType)) return new Column<Int64>( data.Cast<Int64>() ); if (dataType == typeof (DateTime)) return new Column<DateTime>(data.Cast<DateTime>()); if (dataType == typeof (Double)) return new Column<Double>(data.Cast<Double>()); return new Column<String>(data.Cast<String>()); }
public override IEnumerable<Item> Perform(IEnumerable<Item> items, IEnumerable<Item> modItems) { IEnumerable<Wnck.Window> windows = null; if (items.First () is IWindowItem) windows = items.Cast<IWindowItem> ().SelectMany (wi => wi.Windows); else if (items.First () is IApplicationItem) windows = items.Cast<IApplicationItem> ().SelectMany (a => WindowUtils.WindowListForCmd (a.Exec)); if (windows != null) Action (windows); return null; }
private ValidationResult Validate() { IEnumerable DataErrors = this.notifyDataErrorSourceItem?.GetErrors(this.sourcePropertyName) ?? this.dataErrorSourceItem?[this.sourcePropertyName]; ValidationMessage[] Errors = DataErrors?.Cast <object>().Select(_ => (ValidationMessage)_.ToString()).ToArray(); return(this.ProcessValidationResults(Errors)); }
// constructors public BulkInsertOperationArgs( Action<InsertRequest> assignId, bool checkElementNames, string collectionName, string databaseName, int maxBatchCount, int maxBatchLength, int maxDocumentSize, int maxWireDocumentSize, bool isOrdered, BsonBinaryReaderSettings readerSettings, IEnumerable<InsertRequest> requests, WriteConcern writeConcern, BsonBinaryWriterSettings writerSettings) : base( collectionName, databaseName, maxBatchCount, maxBatchLength, maxDocumentSize, maxWireDocumentSize, isOrdered, readerSettings, requests.Cast<WriteRequest>(), writeConcern, writerSettings) { _assignId = assignId; _checkElementNames = checkElementNames; }
public static Type[] GetElementTypes(Type enumerableType, IEnumerable enumerable, ElementTypeFlags flags = ElementTypeFlags.None) { if (enumerableType.HasElementType) { return(new[] { enumerableType.GetElementType() }); } var idictionaryType = enumerableType.GetDictionaryType(); if (idictionaryType != null && flags.HasFlag(ElementTypeFlags.BreakKeyValuePair)) { return(idictionaryType.GetTypeInfo().GenericTypeArguments); } var ienumerableType = enumerableType.GetIEnumerableType(); if (ienumerableType != null) { return(ienumerableType.GetTypeInfo().GenericTypeArguments); } if (typeof(IEnumerable).IsAssignableFrom(enumerableType)) { var first = enumerable?.Cast <object>().FirstOrDefault(); return(new[] { first?.GetType() ?? typeof(object) }); } throw new ArgumentException($"Unable to find the element type for type '{enumerableType}'.", nameof(enumerableType)); }
public void Check(IEnumerable a, IEnumerable b, bool expected) { var cmp = ArrayEqualityComparer <object> .Default; var actual = cmp.Equals(a?.Cast <object>(), b?.Cast <object>()); Assert.AreEqual(expected, actual); }
public CurveCalculated(Guid curveRecipeId, string asOfDate, IEnumerable <IPoint> points) { CurveRecipeId = curveRecipeId; AsOfDate = asOfDate; Points.Add(points?.Cast <Point>() ?? throw new ArgumentNullException(nameof(points))); }
protected override SyntaxNode GenerateOperatorDeclaration(SyntaxNode returnType, string operatorName, IEnumerable<SyntaxNode> parameters, SyntaxNode notImplementedStatement) { Debug.Assert(returnType is TypeSyntax); SyntaxToken operatorToken; switch (operatorName) { case WellKnownMemberNames.EqualityOperatorName: operatorToken = SyntaxFactory.Token(SyntaxKind.EqualsEqualsToken); break; case WellKnownMemberNames.InequalityOperatorName: operatorToken = SyntaxFactory.Token(SyntaxKind.ExclamationEqualsToken); break; case WellKnownMemberNames.LessThanOperatorName: operatorToken = SyntaxFactory.Token(SyntaxKind.LessThanToken); break; case WellKnownMemberNames.GreaterThanOperatorName: operatorToken = SyntaxFactory.Token(SyntaxKind.GreaterThanToken); break; default: return null; } return SyntaxFactory.OperatorDeclaration( default(SyntaxList<AttributeListSyntax>), SyntaxFactory.TokenList(new[] { SyntaxFactory.Token(SyntaxKind.PublicKeyword), SyntaxFactory.Token(SyntaxKind.StaticKeyword) }), (TypeSyntax)returnType, SyntaxFactory.Token(SyntaxKind.OperatorKeyword), operatorToken, SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters.Cast<ParameterSyntax>())), SyntaxFactory.Block((StatementSyntax)notImplementedStatement), default(SyntaxToken)); }
public AddOptimizationsDlg(int optimizationCount, IEnumerable<OptimizationKey> existingOptimizations) { InitializeComponent(); Icon = Resources.Skyline; OptimizationsCount = optimizationCount; if (optimizationCount == 0) labelOptimizationsAdded.Text = Resources.AddOptimizationsDlg_AddOptimizationsDlg_No_new_optimizations_will_be_added_to_the_library_; else if (optimizationCount == 1) labelOptimizationsAdded.Text = Resources.AddOptimizationsDlg_AddOptimizationsDlg__1_new_optimization_will_be_added_to_the_library_; else labelOptimizationsAdded.Text = string.Format(labelOptimizationsAdded.Text, optimizationCount); listExisting.Items.AddRange(existingOptimizations.Cast<object>().ToArray()); labelExisting.Text = string.Format(labelExisting.Text, listExisting.Items.Count); if (listExisting.Items.Count == 0) { panelExisting.Visible = false; Height -= panelExisting.Height; FormBorderStyle = FormBorderStyle.FixedDialog; } }
public void Set(object fromKey, IEnumerable toKeys) { // load existing keys var currentToKeys = GetToKeys(fromKey); // remove missed relations var fromCondition = ComposeFromCondition(fromKey); var deleteCondition = fromCondition; var toKeysArr = toKeys.Cast<object>().ToArray(); if (toKeysArr.Length>0) { deleteCondition = new QueryConditionNode((QField)ToFieldName, Conditions.In | Conditions.Not, new QConst(toKeysArr)) & deleteCondition; } Dalc.Delete(new Query(RelationSourceName, deleteCondition)); var data = ExtraKeys == null ? new Hashtable() : new Hashtable( new DictionaryWrapper<string,object>(ExtraKeys) ); data[FromFieldName] = fromKey; int pos = 1; foreach (var toKey in toKeys) { data[ToFieldName] = toKey; if (PositionFieldName != null) data[PositionFieldName] = pos++; if (Contains(toKey, currentToKeys)) { if (PositionFieldName!=null) Dalc.Update( new Hashtable() { {PositionFieldName, data[PositionFieldName]} }, new Query(RelationSourceName, (QField)ToFieldName == new QConst(toKey) & fromCondition)); } else { Dalc.Insert(data, RelationSourceName); } } }
public IDictionary <RelationshipAttribute, IEnumerable> LoadImplicitlyAffected(IDictionary <RelationshipAttribute, IEnumerable> leftResourcesByRelation, IEnumerable existingRightResources = null) { List <IIdentifiable> existingRightResourceList = existingRightResources?.Cast <IIdentifiable>().ToList(); var implicitlyAffected = new Dictionary <RelationshipAttribute, IEnumerable>(); foreach (KeyValuePair <RelationshipAttribute, IEnumerable> pair in leftResourcesByRelation) { RelationshipAttribute relationship = pair.Key; IEnumerable lefts = pair.Value; if (relationship is HasManyThroughAttribute) { continue; } // note that we don't have to check if BeforeImplicitUpdate hook is implemented. If not, it wont ever get here. IEnumerable includedLefts = LoadDbValues(relationship.LeftType, lefts, relationship); AddToImplicitlyAffected(includedLefts, relationship, existingRightResourceList, implicitlyAffected); } return(implicitlyAffected.ToDictionary(pair => pair.Key, pair => CollectionConverter.CopyToHashSet(pair.Value, pair.Key.RightType))); }
/// <summary> /// Loads the given target faces /// </summary> public virtual void SetTargetFaces(IEnumerable<ITargetFace> faces) { if (!faces.All(x => x is IFaceModelTargetFace)) throw new ArgumentException("All target faces must implement IFaceModelTargetFace!"); this.SetTargetFaces(faces.Cast<IFaceModelTargetFace>()); }
public static Type GetElementType(Type enumerableType, IEnumerable enumerable) { if (enumerableType.HasElementType) { return(enumerableType.GetElementType()); } if (enumerableType.IsGenericType() && enumerableType.GetGenericTypeDefinition() == typeof(IEnumerable <>)) { return(enumerableType.GetTypeInfo().GenericTypeArguments[0]); } Type ienumerableType = GetIEnumerableType(enumerableType); if (ienumerableType != null) { return(ienumerableType.GetTypeInfo().GenericTypeArguments[0]); } if (typeof(IEnumerable).IsAssignableFrom(enumerableType)) { var first = enumerable?.Cast <object>().FirstOrDefault(); return(first?.GetType() ?? typeof(object)); } throw new ArgumentException($"Unable to find the element type for type '{enumerableType}'.", nameof(enumerableType)); }
void createReferenceMembers(IEnumerable<IExtendedMemberInfo> xpCollection){ XPDictionary xpDictionary = XafTypesInfo.XpoTypeInfoSource.XPDictionary; foreach (var info in xpCollection.Cast<IExtendedReferenceMemberInfo>()){ XPCustomMemberInfo member = xpDictionary.GetClassInfo(info.Owner).CreateMember(info.Name, info.ReferenceType); createAttributes(info, member); } }
public DownloadList SoftAdd(IEnumerable entries, MediaType mediaType) { var downloadList = new DownloadList(mediaType, OnDownloadStatusChange); foreach (var member in entries.Cast<YoutubeEntry>().Where(member => member.Uri != null)) downloadList.Entries.Add(member.Clone()); if (downloadList.Entries.Count > 0) Entries.Add(downloadList); return downloadList; }
public override object CreateMultiResolutionImage (IEnumerable<object> images) { var refImg = (GtkImage) images.First (); var f = refImg.Frames [0]; var frames = images.Cast<GtkImage> ().Select (img => new GtkImage.ImageFrame (img.Frames[0].Pixbuf, f.Width, f.Height, true)); return new GtkImage (frames); }
private static dynamic GetNonEnglishTweet(dynamic timeline) { const string englishLanguageCode = "en"; IEnumerable enumerable = timeline as IEnumerable; return(enumerable?.Cast <dynamic>().FirstOrDefault(obj => obj.lang != englishLanguageCode)); }
private void OnItemsSourceChanged(IEnumerable oldValue, IEnumerable newValue) { // Remove handler for oldValue.CollectionChanged (if present) INotifyCollectionChanged oldValueINotifyCollectionChanged = oldValue as INotifyCollectionChanged; if (null != oldValueINotifyCollectionChanged) { oldValueINotifyCollectionChanged.CollectionChanged -= new NotifyCollectionChangedEventHandler(ItemsSourceCollectionChanged); } // Add handler for newValue.CollectionChanged (if possible) INotifyCollectionChanged newValueINotifyCollectionChanged = newValue as INotifyCollectionChanged; if (null != newValueINotifyCollectionChanged) { newValueINotifyCollectionChanged.CollectionChanged += new NotifyCollectionChangedEventHandler(ItemsSourceCollectionChanged); } // Store a local cached copy of the data Items = newValue == null ? null : new List<object>(newValue.Cast<object>().ToList()); // Clear and set the view on the selection adapter ClearView(); if (SelectionAdapter != null && SelectionAdapter.ItemsSource != View) { SelectionAdapter.ItemsSource = View; } }
public List<int> Shuffle(IEnumerable<int> cards) { int[] castedArray = cards.Cast<int>().ToArray(); int[] arr = ShuffleMethod(castedArray); var list = new List<int>(arr); return (list); }
public override void Fill(IEnumerable<object> Items) { if (Items != null) { Items.Cast<System.Data.DataRow>().Fill(); } }
/// <inheritdoc/> public void Run(IEnumerable<ITestCase> testMethods, IMessageSink messageSink) { bool cancelled = false; var totalSummary = new RunSummary(); string currentDirectory = Directory.GetCurrentDirectory(); try { Directory.SetCurrentDirectory(Path.GetDirectoryName(assemblyInfo.AssemblyPath)); if (messageSink.OnMessage(new TestAssemblyStarting())) { var classGroups = testMethods.Cast<XunitTestCase>().GroupBy(tc => tc.Class).ToList(); if (classGroups.Count > 0) { var collectionSummary = new RunSummary(); if (messageSink.OnMessage(new TestCollectionStarting())) { foreach (var group in classGroups) { var classSummary = new RunSummary(); if (!messageSink.OnMessage(new TestClassStarting { ClassName = group.Key.Name })) cancelled = true; else { cancelled = RunTestClass(messageSink, group, classSummary); collectionSummary.Aggregate(classSummary); } if (!messageSink.OnMessage(new TestClassFinished { Assembly = assemblyInfo, ClassName = group.Key.Name, TestsRun = classSummary.Total })) cancelled = true; if (cancelled) break; } } messageSink.OnMessage(new TestCollectionFinished { Assembly = assemblyInfo, TestsRun = collectionSummary.Total }); totalSummary.Aggregate(collectionSummary); } } messageSink.OnMessage(new TestAssemblyFinished { Assembly = assemblyInfo, TestsRun = totalSummary.Total, TestsFailed = totalSummary.Failed, TestsSkipped = totalSummary.Skipped, ExecutionTime = totalSummary.Time }); } finally { Directory.SetCurrentDirectory(currentDirectory); } }
public static bool HasSameItemsRegardlessOfSortOrder(this IEnumerable left, IEnumerable right) { var leftCollection = left.Cast<object>().ToList(); var rightCollection = right.Cast<object>().ToList(); return leftCollection.Except(rightCollection).Count() == 0; }
void createCoreMembers(IEnumerable<IExtendedMemberInfo> collection){ XPDictionary xpDictionary = XafTypesInfo.XpoTypeInfoSource.XPDictionary; foreach (var info in collection.Cast<IExtendedCoreTypeMemberInfo>()){ XPCustomMemberInfo member = xpDictionary.GetClassInfo(info.Owner).CreateMember(info.Name, Type.GetType("System." + info.DataType, true)); createAttributes(info, member); } }
public override IEnumerable<Item> Perform(IEnumerable<Item> items, IEnumerable<Item> modifierItems) { string search_text; search_text = (items.First () as ITextItem).Text; return GCal.SearchEvents (modifierItems.Cast<GCalendarItem> (), search_text).Cast<Item> (); }
public Run(IEnumerable<Assembly> assemblies) : base(assemblies.Cast<SpecificationContainer>()) { _assemblies = assemblies; _totalAssemblies = assemblies.Count(); _totalConcerns = assemblies.Sum(x => x.TotalConcerns); _totalContexts = assemblies.Sum(x => x.TotalContexts); }
// constructors public BulkDeleteOperationArgs( string collectionName, string databaseName, int maxBatchCount, int maxBatchLength, int maxDocumentSize, int maxWireDocumentSize, bool isOrdered, BsonBinaryReaderSettings readerSettings, IEnumerable<DeleteRequest> requests, WriteConcern writeConcern, BsonBinaryWriterSettings writerSettings) : base( collectionName, databaseName, maxBatchCount, maxBatchLength, maxDocumentSize, maxWireDocumentSize, isOrdered, readerSettings, requests.Cast<WriteRequest>(), writeConcern, writerSettings) { }
public AddIrtSpectralLibrary(IEnumerable<LibrarySpec> librarySpecs) { InitializeComponent(); comboLibrary.Items.AddRange(librarySpecs.Cast<object>().ToArray()); ComboHelper.AutoSizeDropDown(comboLibrary); }
public static Type GetElementType(Type enumerableType, IEnumerable enumerable) { if (enumerableType.HasElementType) { return enumerableType.GetElementType(); } if (enumerableType.IsGenericType && enumerableType.GetGenericTypeDefinition().Equals(typeof(IEnumerable<>))) { return enumerableType.GetGenericArguments()[0]; } Type ienumerableType = enumerableType.GetInterface("IEnumerable`1"); if (ienumerableType != null) { return ienumerableType.GetGenericArguments()[0]; } if (typeof(IEnumerable).IsAssignableFrom(enumerableType)) { if (enumerable != null) { var first = enumerable.Cast<object>().FirstOrDefault(); if (first != null) return first.GetType(); } return typeof(object); } throw new ArgumentException(String.Format("Unable to find the element type for type '{0}'.", enumerableType), "enumerableType"); }
private Settings(int height, int width, IEnumerable <string> links) { Height = height; Width = width; Links = links?.Cast <string>().ToList(); }
/// <summary> /// Inherited from <see cref="IValidationManager"/>. /// <para> /// This manager assumes all objects within <paramref name="validationResult"/> are of type <see cref="ValidationResult"/>. /// </para> /// <para> /// This manager assumes all <see cref="ValidationResult"/> objects within <paramref name="validationResult"/> that /// have an empty <see cref="P:ValidationResult.MemberNames"/> collection are top level or class level issues. /// </para> /// </summary> /// <param name="errorCollection">A <see cref="ValidationErrorCollection"/> that houses the validation results.</param> /// <param name="validationResult">A <see cref="IEnumerable{T}"/> that represents the collection of validation issues that need to be applied to <paramref name="errorCollection"/>.</param> public virtual void SetErrors(ValidationErrorCollection errorCollection, IEnumerable<object> validationResult) { lock (_syncObject) { IEnumerable<ValidationResult> vResults = validationResult.Cast<ValidationResult>(); var results = (from g in (from tuple in (from r in vResults from name in r.MemberNames select new Tuple<string, ValidationResult>(name, r)) group tuple by tuple.Item1) select new Tuple<string, IEnumerable<ValidationResult>>(g.Key, g.Select(a => a.Item2))).ToArray(); if (vResults.Any(a => a.MemberNames.Count() == 0)) { Tuple<string, IEnumerable<ValidationResult>> newTuple = new Tuple<string, IEnumerable<ValidationResult>>(string.Empty, from vr in vResults where vr.MemberNames.Count() == 0 select vr); results = results.Concat(new Tuple<string, IEnumerable<ValidationResult>>[] { newTuple }).ToArray(); } errorCollection.Clear(); foreach (Tuple<string, IEnumerable<ValidationResult>> item in results) errorCollection.SetErrors(item.Item1, item.Item2.Cast<object>()); } }
internal DataRow(DataTable table, IEnumerable cells) { Table = table; _objects = table.Columns.Cast<DataColumn>() .Zip(cells.Cast<object>(), Tuple.Create) .ToDictionary(tuple => tuple.Item1, tuple => tuple.Item2); }
public void Process(IEnumerable<object> rawEvents) { var events = rawEvents.Cast<string>(); var output = new List<string>(); output.Add(""); var setgewinner = events.Where(e => e.StartsWith("Setgewinn:")) .Select(e => int.Parse(e.Split(':')[1])) .GroupBy(spielerIndex => spielerIndex) .Select(spielerIndex => new {Spielerindex=spielerIndex.Key, Spielgewinne=spielerIndex.Count()}); int[] setgewinne = new int[2]; setgewinner.ToList().ForEach(sg => setgewinne[sg.Spielerindex] = sg.Spielgewinne); output.Add(string.Format("Winner: Player {0} with {1} : {2}", setgewinne[0]>setgewinne[1] ? "A" : "B", setgewinne[0], setgewinne[1])); // Die weitere Formatierung der Ausgabe spare ich mir. // Die Daten lassen sich leicht aus den Events herauslesen. output.Add(""); Result(output.ToArray()); }
public RecycleViewAdapter(HorizontalListView element, RecyclerView parentView, Context context) { _element = element; _weakParentView = new WeakReference <RecyclerView>(parentView); _context = context; _elementItemsSource = element.ItemsSource; _dataSource = _elementItemsSource?.Cast <object>().ToList() ?? new List <object>(); _formsViews = new List <WeakReference <ViewCell> >(); if (!(_element.ItemTemplate is DataTemplateSelector)) { // Cache only support single DataTemplate _viewHolderQueue = new ViewHolderQueue(element.ViewCacheSize, () => CreateViewHolder()); _viewHolderQueue.Build(); } _notifyCollectionChanged = _elementItemsSource as INotifyCollectionChanged; if (_notifyCollectionChanged != null) { _notifyCollectionChanged.CollectionChanged += OnCollectionChanged; } }
private static void ImplementIsOnlyMadeOf <T>(ICheckLogic <IEnumerable <T> > checker, IEnumerable expectedValues) { checker. DefineExpectedValues(expectedValues?.Cast <object>(), expectedValues.Count(), comparison: "only elements from", negatedComparison: "at least one element different from"). FailWhen(sut => sut == null & expectedValues != null, "The {0} is null and thus, does not contain exactly the given value(s)."). Analyze((sut, test) => { if (sut == null && expectedValues == null) { return; } var unexpectedValuesFound = ExtractUnexpectedValues(sut, expectedValues); if (unexpectedValuesFound.Count <= 0) { return; } test.Fail( string.Format( "The {{0}} does not contain only the given value(s)." + Environment.NewLine + "It contains also other values:" + Environment.NewLine + "\t{0}", unexpectedValuesFound.ToStringProperlyFormatted().DoubleCurlyBraces())); }). OnNegate("The {0} contains only the given values whereas it must not.").EndCheck(); }
public Assembly(string name, IEnumerable<Concern> concerns) : base(concerns.Cast<SpecificationContainer>()) { _name = name; _concerns = concerns.OrderBy(x => x.Name).ToList(); _totalConerns = concerns.Count(); _totalContexts = concerns.Sum(x => x.TotalContexts); }
public AddIrtCalculatorDlg(IEnumerable<RCalcIrt> calculators) { InitializeComponent(); comboLibrary.Items.AddRange(calculators.Cast<object>().ToArray()); ComboHelper.AutoSizeDropDown(comboLibrary); }
/// <summary> /// 设置指定属性的验证错误。 /// </summary> /// <param name="errors">属性的验证错误。</param> /// <param name="propertyName">要设置验证错误的属性的名称。</param> /// <exception cref="InvalidOperationException"> /// <paramref name="propertyName"/> 为 <see langword="null"/> 或空字符串。</exception> protected virtual void SetErrors( IEnumerable?errors, [CallerMemberName] string?propertyName = null) { if (this.IsEntityName(propertyName)) { throw new InvalidOperationException(); } var entityHadErrors = this.HasErrors; var hadErrors = this.ContainsErrors(propertyName); var hasErrors = errors?.Cast <object>().Any() ?? false; if (hasErrors) { this.ValidationErrors[propertyName] = errors !; } else { this.ValidationErrors.TryRemove(propertyName, out errors !); } var errorsChanged = hadErrors || hasErrors; if (errorsChanged) { this.NotifyErrorsChanged(propertyName); } var hasErrorsChanged = entityHadErrors ^ this.HasErrors; if (hasErrorsChanged) { this.RelatedNotifyPropertyChanged(nameof(this.HasErrors)); } }
public static int GetHashCode(IEnumerable enumerable, IEqualityComparer <object> comparer) { unchecked { // NOTE: The sequence does not define order, so just XOR all elements return(enumerable?.Cast <object> ( ).Aggregate(17, (current, item) => current ^ comparer.GetHashCode(item)) ?? 0); } }
public ReadOnlyComponent( string name, string description, ComponentStatus status, IEnumerable <ReadOnlyComponent> subComponents) : this(name, description, status, subComponents?.Cast <IReadOnlyComponent>()) { }
public static int GetHashCode(IEnumerable enumerable, IEqualityComparer <object> comparer) { unchecked { // NOTE: Ensure that different order produces different hash codes return(enumerable?.Cast <object> ( ).Aggregate(17, (current, item) => (current * 486187739) ^ comparer.GetHashCode(item)) ?? 0); } }
/// <summary> /// Returns the number of items present within the specified enumerable (returns 0 if the enumerable is null). /// </summary> /// <param name="enumerable">The enumerable.</param> /// <returns>The number of items present within the specified enumerable (returns 0 if the enumerable is null).</returns> public static long Count(this IEnumerable enumerable) { if (enumerable is ICollection collec) { return(collec.Count); } return(enumerable?.Cast <object>().LongCount() ?? 0); }
public bool Add <T>(System.Guid guid, IEnumerable <T> elements) where T : Element { if (guid == System.Guid.Empty) { return(false); } objects[guid.ToString()] = elements?.Cast <object>().ToList(); return(true); }
public bool Add <T>(ElementId elementId, IEnumerable <T> sAMObjects) where T : IJSAMObject { if (elementId == null || elementId == ElementId.InvalidElementId) { return(false); } objects[elementId.IntegerValue.ToString()] = sAMObjects?.Cast <object>().ToList(); return(true); }
public ParsedProcedureInfo( string procedureId, string procedureNumber, string resultType, IEnumerable parameters) { ProcedureId = procedureId; ProcedureNumber = procedureNumber; ResultType = resultType; Parameters = parameters?.Cast <ParsedDeclaration>().ToList() ?? new List <ParsedDeclaration>(); }
/// <inheritdoc /> public void DeleteByIds(IEnumerable ids) { var cast = ids?.Cast <object>().ToList() ?? new List <object>(); var urnKeys = cast.Select(t => this._client.UrnKey <T>(t)).ToList(); if (urnKeys.Count > 0) { this.RemoveEntry(urnKeys.ToArray()); this._client.RemoveTypeIds <T>(cast.Select(x => x.ToString()).ToArray()); } }
/// <summary> /// Gets the item at the specified index in a collection. /// </summary> /// <param name="items">The collection.</param> /// <param name="index">The index.</param> /// <returns>The index of the item or -1 if the item was not found.</returns> protected static object ElementAt(IEnumerable items, int index) { var typedItems = items?.Cast <object>(); if (index != -1 && typedItems != null && index < typedItems.Count()) { return(typedItems.ElementAt(index) ?? null); } else { return(null); } }
public ILazyChildren Clone(bool forceVisit, Func <IModelObject, IModelObject> update, IEnumerable <IModelObject> added = null, IEnumerable <IModelObject> deleted = null) { if (update == null) { throw new ArgumentNullException(nameof(update)); } return(new LazyChildren <TChild>(parent => Children .Except(deleted?.Cast <TChild>() ?? Enumerable.Empty <TChild>()) .Select(c => (TChild)update.Invoke(c) ?? throw new ObjectNotFoundException("No child returned while cloning children.")) .Union(added?.Cast <TChild>() ?? Enumerable.Empty <TChild>()) .ToImmutableList()) { ForceVisit = ForceVisit || forceVisit, });
public IXLRange ReplaceData(IEnumerable data, bool transpose, Boolean propagateExtraColumns = false) { var castedData = data?.Cast <object>(); if (!(castedData?.Any() ?? false) || data is String) { throw new InvalidOperationException("Cannot replace table data with empty enumerable."); } var firstDataRowNumber = this.DataRange.FirstRow().RowNumber(); var lastDataRowNumber = this.DataRange.LastRow().RowNumber(); // Resize table var sizeDifference = castedData.Count() - this.DataRange.RowCount(); if (sizeDifference > 0) { this.DataRange.LastRow().InsertRowsBelow(sizeDifference); } else if (sizeDifference < 0) { this.DataRange.Rows ( lastDataRowNumber + sizeDifference + 1 - firstDataRowNumber + 1, lastDataRowNumber - firstDataRowNumber + 1 ) .Delete(); // No propagation needed when reducing the number of rows propagateExtraColumns = false; } if (sizeDifference != 0) { // Invalidate table fields' columns this.Fields.Cast <XLTableField>().ForEach(f => f.Column = null); } var replacedRange = this.DataRange.FirstCell().InsertData(castedData, transpose); if (propagateExtraColumns) { PropagateExtraColumns(replacedRange.ColumnCount(), lastDataRowNumber); } return(replacedRange); }
public CheckBoxView(string title, string message, IEnumerable source, IEnumerable selecteds) { InitializeComponent(); BindTexts(title, message); var _selecteds = selecteds?.Cast <object>(); foreach (var item in source) { slContent.Children.Add(new CheckBox(item?.ToString(), -1) { //TODO: will be changed later CommandParameter = item, IsChecked = _selecteds?.Contains(item) ?? false, Type = CrossDiaglogKit.GlobalSettings.CheckBoxType, }); } }
public SqlList(IEnumerable values) { object[] arr = values?.Cast <object>() .ToArray(); if (arr == null || arr.Length == 0) { // ensuring at least one item to avoid building an empty list // e.g. foo IN () arr = new object[1] { null }; } this.values = arr; }
public IXamlIlMethodBuilder DefineMethod(IXamlIlType returnType, IEnumerable <IXamlIlType> args, string name, bool isPublic, bool isStatic, bool isInterfaceImpl, IXamlIlMethod overrideMethod) { var ret = ((SreType)returnType).Type; var argTypes = args?.Cast <SreType>().Select(t => t.Type) ?? Type.EmptyTypes; var m = _tb.DefineMethod(name, (isPublic ? MethodAttributes.Public : MethodAttributes.Private) | (isStatic ? MethodAttributes.Static : default(MethodAttributes)) | (isInterfaceImpl ? MethodAttributes.Virtual | MethodAttributes.NewSlot : default(MethodAttributes)) , ret, argTypes.ToArray()); if (overrideMethod != null) { _tb.DefineMethodOverride(m, ((SreMethod)overrideMethod).Method); } return(new SreMethodBuilder(_system, m)); }
/// <summary> /// Initialise an ErrorSeries instance. /// </summary> /// <param name="title">Name of the series.</param> /// <param name="colour">Colour of the series.</param> /// <param name="showLegend">Should this series appear in the legend?</param> /// <param name="x">X-axis data.</param> /// <param name="y">Y-axis data.</param> /// <param name="line">The line settings for the graph (thickness, type, ...).</param> /// <param name="marker">The marker settings for the graph (size, shape, ...).</param> /// <param name="barThickness">Thickness of the error bars.</param> /// <param name="stopperThickness">Thickness of the stopper on the error bars.</param> /// <param name="xError">Error data for the x series.</param> /// <param name="yError">Error data for the y series.</param> /// <param name="xName">Name of the x-axis field displayed by this series.</param> /// <param name="yName">Name of the y-axis field displayed by this series.</param> public ErrorSeries(string title, Color colour, bool showLegend, IEnumerable <double> x, IEnumerable <double> y, Line line, Marker marker, LineThickness barThickness, LineThickness stopperThickness, IEnumerable <double> xError, IEnumerable <double> yError, string xName, string yName) : base(title, colour, showLegend, x, y, line, marker, xName, yName) { BarThickness = barThickness; StopperThickness = stopperThickness; XError = xError?.Cast <object>() ?? Enumerable.Empty <object>(); YError = yError?.Cast <object>() ?? Enumerable.Empty <object>(); }
public RecycleViewAdapter(HorizontalListView element, Context context) { _element = element; _context = context; _elementItemsSource = element.ItemsSource; _dataSource = _elementItemsSource?.Cast <object>().ToList() ?? new List <object>(); _formsViews = new List <WeakReference <ViewCell> >(); _viewHolderQueue = new ViewHolderQueue(element.ViewCacheSize, CreateViewHolder); _viewHolderQueue.Build(); _notifyCollectionChanged = _elementItemsSource as INotifyCollectionChanged; if (_notifyCollectionChanged != null) { _notifyCollectionChanged.CollectionChanged += OnCollectionChanged; } }
private void CompareByEquality(IEnumerable original, IEnumerable current, IMemberOptions options) { var originalList = original?.Cast <object>().ToList() ?? new List <object>(); var currentList = current?.Cast <object>().ToList() ?? new List <object>(); var currentPath = CurrentPath(); var currentName = CurrentName(); var compare = options?.Equality ?? Equals; _pathStack.Pop(); for (int index = 0; index < currentList.Count; index++) { string p = $"{currentPath}[{index}]"; var v = currentList[index]; var o = originalList.FirstOrDefault(f => compare(f, v)); if (o == null) { // added item CreateChange(ChangeOperation.Add, null, v, p, currentName); continue; } // remove so can't be reused originalList.Remove(o); var t = o.GetType(); _pathStack.Push(p); CompareType(t, o, v, options); _pathStack.Pop(); } _pathStack.Push(currentPath); // removed items foreach (var v in originalList) { CreateChange(ChangeOperation.Remove, v, null); } }
public IXLRange AppendData(IEnumerable data, bool transpose, Boolean propagateExtraColumns = false) { var castedData = data?.Cast <object>(); if (!(castedData?.Any() ?? false) || data is String) { return(null); } var numberOfNewRows = castedData.Count(); var lastRowOfOldRange = this.DataRange.LastRow(); lastRowOfOldRange.InsertRowsBelow(numberOfNewRows); this.Fields.Cast <XLTableField>().ForEach(f => f.Column = null); var insertedRange = lastRowOfOldRange.RowBelow().FirstCell().InsertData(castedData, transpose); PropagateExtraColumns(insertedRange.ColumnCount(), lastRowOfOldRange.RowNumber()); return(insertedRange); }
public Dictionary <RelationshipAttribute, IEnumerable> LoadImplicitlyAffected( Dictionary <RelationshipAttribute, IEnumerable> leftResourcesByRelation, IEnumerable existingRightResources = null) { var existingRightResourceList = existingRightResources?.Cast <IIdentifiable>().ToList(); var implicitlyAffected = new Dictionary <RelationshipAttribute, IEnumerable>(); foreach (var kvp in leftResourcesByRelation) { if (IsHasManyThrough(kvp, out var lefts, out var relationship)) { continue; } // note that we don't have to check if BeforeImplicitUpdate hook is implemented. If not, it wont ever get here. var includedLefts = LoadDbValues(relationship.LeftType, lefts, ResourceHook.BeforeImplicitUpdateRelationship, relationship); AddToImplicitlyAffected(includedLefts, relationship, existingRightResourceList, implicitlyAffected); } return(implicitlyAffected.ToDictionary(kvp => kvp.Key, kvp => TypeHelper.CreateHashSetFor(kvp.Key.RightType, kvp.Value))); }