These are good points, thanks for the correction. Computes the average of a sequence of Decimal values that are obtained by invoking a transform function on each element of the input sequence. you dont use the iterator of this IEnumerable. In the following example, assume that a product object (p) contains many fields and methods, and that you are only interested in creating a sequence of objects that contain the product name and the unit price. I think the cleanest way to optimize it and to use only one loop is to first get the values with a select, create key/value pairs there and then filter by value: private static IEnumerable<KeyValuePair<string, string>> GetPropertyValues(MyClass myClass) { return PropertyDictionary .Select(kvp => new KeyValuePair<string, string> ( kvp.Key . Returns a new enumerable collection that contains the elements from source with the last count elements of the source collection omitted. . The object initializers syntax allows you to create an instance, and after that it assigns the newly created object, with its assigned properties, to the variable in the assignment. IEnumerable vs List - What to Use? Returns a specified number of contiguous elements from the start of a sequence. You could also initialize dictionaries and other associative containers using the following syntax. Some of the answers above suggest using IList instead of IEnumerable. Or you need to iterate over it to get the current value from collection. Some classes may have collection properties where the property is read-only, like the Cats property of CatOwner in the following case: You will not be able to use collection initializer syntax discussed so far since the property cannot be assigned a new list: However, new entries can be added to Cats nonetheless using the initialization syntax by omitting the list creation (new List), as shown next: The set of entries to be added simply appear surrounded by braces. Returns the element at a specified index in a sequence or a default value if the index is out of range. Determines whether a sequence contains a specified element by using a specified IEqualityComparer. Adds a value to the beginning of the sequence. More info about Internet Explorer and Microsoft Edge, Covariance and Contravariance in Generics, Microsoft.Extensions.Configuration.Memory.MemoryConfigurationProvider, Microsoft.Extensions.DependencyInjection.IServiceCollection, Microsoft.Extensions.DependencyInjection.ServiceCollection, Microsoft.Extensions.DiagnosticAdapter.Internal.ProxyEnumerable, Microsoft.Extensions.DiagnosticAdapter.Internal.ProxyList, Microsoft.Extensions.FileProviders.Composite.CompositeDirectoryContents, Microsoft.Extensions.FileProviders.IDirectoryContents, Microsoft.Extensions.FileProviders.Internal.PhysicalDirectoryContents, Microsoft.Extensions.FileProviders.NotFoundDirectoryContents, Microsoft.Extensions.Logging.FilterLoggerSettings, Microsoft.Extensions.Logging.Internal.FormattedLogValues, Microsoft.Extensions.Primitives.StringTokenizer, Microsoft.Extensions.Primitives.StringValues, System.Activities.Presentation.ContextItemManager, System.Activities.Presentation.Model.ModelItemCollection, System.Activities.Presentation.Model.ModelItemDictionary, System.Activities.Presentation.Model.ModelMemberCollection, System.Activities.Presentation.PropertyEditing.PropertyEntryCollection, System.Activities.Presentation.PropertyEditing.PropertyValueCollection, System.Activities.Presentation.ServiceManager, System.Activities.Presentation.Toolbox.ToolboxCategoryItems, System.Collections.Concurrent.BlockingCollection, System.Collections.Concurrent.ConcurrentBag, System.Collections.Concurrent.ConcurrentDictionary, System.Collections.Concurrent.ConcurrentQueue, System.Collections.Concurrent.ConcurrentStack, System.Collections.Concurrent.IProducerConsumerCollection, System.Collections.Frozen.FrozenDictionary, System.Collections.Generic.Dictionary, System.Collections.Generic.Dictionary.KeyCollection, System.Collections.Generic.Dictionary.ValueCollection, System.Collections.Generic.ICollection, System.Collections.Generic.IDictionary, System.Collections.Generic.IReadOnlyCollection, System.Collections.Generic.IReadOnlyDictionary, System.Collections.Generic.IReadOnlyList, System.Collections.Generic.IReadOnlySet, System.Collections.Generic.PriorityQueue.UnorderedItemsCollection, System.Collections.Generic.SortedDictionary, System.Collections.Generic.SortedDictionary.KeyCollection, System.Collections.Generic.SortedDictionary.ValueCollection, System.Collections.Generic.SortedList, System.Collections.Generic.SynchronizedCollection, System.Collections.Generic.SynchronizedReadOnlyCollection, System.Collections.Immutable.IImmutableDictionary, System.Collections.Immutable.IImmutableList, System.Collections.Immutable.IImmutableQueue, System.Collections.Immutable.IImmutableSet, System.Collections.Immutable.IImmutableStack, System.Collections.Immutable.ImmutableArray, System.Collections.Immutable.ImmutableArray.Builder, System.Collections.Immutable.ImmutableDictionary, System.Collections.Immutable.ImmutableDictionary.Builder, System.Collections.Immutable.ImmutableHashSet, System.Collections.Immutable.ImmutableHashSet.Builder, System.Collections.Immutable.ImmutableList, System.Collections.Immutable.ImmutableList.Builder, System.Collections.Immutable.ImmutableQueue, System.Collections.Immutable.ImmutableSortedDictionary, System.Collections.Immutable.ImmutableSortedDictionary.Builder, System.Collections.Immutable.ImmutableSortedSet, System.Collections.Immutable.ImmutableSortedSet.Builder, System.Collections.Immutable.ImmutableStack, System.Collections.ObjectModel.Collection, System.Collections.ObjectModel.ReadOnlyCollection, System.Collections.ObjectModel.ReadOnlyDictionary, System.Collections.ObjectModel.ReadOnlyDictionary.KeyCollection, System.Collections.ObjectModel.ReadOnlyDictionary.ValueCollection, System.ComponentModel.Composition.Primitives.ComposablePartCatalog, System.Data.Common.DbBatchCommandCollection, System.Data.EnumerableRowCollection, System.Data.Linq.ChangeConflictCollection, System.Data.Objects.DataClasses.EntityCollection, System.Data.Objects.ObjectParameterCollection, System.Data.Services.Client.DataServiceQuery, System.Data.Services.Client.DataServiceResponse, System.Data.Services.Client.QueryOperationResponse, System.Diagnostics.ActivityTagsCollection, System.DirectoryServices.AccountManagement.PrincipalCollection, System.DirectoryServices.AccountManagement.PrincipalSearchResult, System.DirectoryServices.AccountManagement.PrincipalValueCollection, System.IdentityModel.Tokens.SecurityKeyIdentifier, System.IO.Enumeration.FileSystemEnumerable, System.IO.Packaging.PackagePartCollection, System.IO.Packaging.PackageRelationshipCollection, System.Net.Http.Headers.HeaderStringValues, System.Net.Http.Headers.HttpHeadersNonValidated, System.Net.Http.Headers.HttpHeaderValueCollection, System.Net.NetworkInformation.GatewayIPAddressInformationCollection, System.Net.NetworkInformation.IPAddressCollection, System.Net.NetworkInformation.IPAddressInformationCollection, System.Net.NetworkInformation.MulticastIPAddressInformationCollection, System.Net.NetworkInformation.UnicastIPAddressInformationCollection, System.Reflection.Metadata.AssemblyFileHandleCollection, System.Reflection.Metadata.AssemblyReferenceHandleCollection, System.Reflection.Metadata.BlobBuilder.Blobs, System.Reflection.Metadata.CustomAttributeHandleCollection, System.Reflection.Metadata.CustomDebugInformationHandleCollection, System.Reflection.Metadata.DeclarativeSecurityAttributeHandleCollection, System.Reflection.Metadata.DocumentHandleCollection, System.Reflection.Metadata.EventDefinitionHandleCollection, System.Reflection.Metadata.ExportedTypeHandleCollection, System.Reflection.Metadata.FieldDefinitionHandleCollection, System.Reflection.Metadata.GenericParameterConstraintHandleCollection, System.Reflection.Metadata.GenericParameterHandleCollection, System.Reflection.Metadata.ImportDefinitionCollection, System.Reflection.Metadata.ImportScopeCollection, System.Reflection.Metadata.InterfaceImplementationHandleCollection, System.Reflection.Metadata.LocalConstantHandleCollection, System.Reflection.Metadata.LocalScopeHandleCollection, System.Reflection.Metadata.LocalVariableHandleCollection, System.Reflection.Metadata.ManifestResourceHandleCollection, System.Reflection.Metadata.MemberReferenceHandleCollection, System.Reflection.Metadata.MethodDebugInformationHandleCollection, System.Reflection.Metadata.MethodDefinitionHandleCollection, System.Reflection.Metadata.MethodImplementationHandleCollection, System.Reflection.Metadata.ParameterHandleCollection, System.Reflection.Metadata.PropertyDefinitionHandleCollection, System.Reflection.Metadata.SequencePointCollection, System.Reflection.Metadata.TypeDefinitionHandleCollection, System.Reflection.Metadata.TypeReferenceHandleCollection, System.Runtime.CompilerServices.ConditionalWeakTable, System.Runtime.CompilerServices.ReadOnlyCollectionBuilder, System.Security.Cryptography.Cose.CoseHeaderMap, System.Security.Cryptography.X509Certificates.X509Certificate2Collection, System.Security.Cryptography.X509Certificates.X509ChainElementCollection, System.Security.Cryptography.X509Certificates.X509ExtensionCollection, System.Security.Principal.IdentityReferenceCollection, System.ServiceModel.Channels.MessageHeaders, System.ServiceModel.Channels.MessageProperties, System.ServiceModel.Channels.UnderstoodHeaders, System.ServiceModel.Configuration.CustomBindingElement, System.ServiceModel.Configuration.ServiceModelExtensionCollectionElement, System.ServiceModel.Dispatcher.IMessageFilterTable, System.ServiceModel.Dispatcher.MessageFilterTable, System.ServiceModel.Dispatcher.MessageQueryTable, System.ServiceModel.Dispatcher.XPathMessageFilterTable, System.ServiceModel.ExtensionCollection, System.ServiceModel.IExtensionCollection, System.Text.Json.JsonElement.ArrayEnumerator, System.Text.Json.JsonElement.ObjectEnumerator, System.Text.RegularExpressions.CaptureCollection, System.Text.RegularExpressions.GroupCollection, System.Text.RegularExpressions.MatchCollection, System.Web.ModelBinding.ModelBinderDictionary, System.Web.ModelBinding.ModelStateDictionary, System.Web.Services.Description.BasicProfileViolationCollection, System.Windows.Controls.ColumnDefinitionCollection, System.Windows.Controls.RowDefinitionCollection, System.Windows.Data.XmlNamespaceMappingCollection, System.Windows.Documents.DocumentReferenceCollection, System.Windows.Documents.DocumentStructures.FigureStructure, System.Windows.Documents.DocumentStructures.ListItemStructure, System.Windows.Documents.DocumentStructures.ListStructure, System.Windows.Documents.DocumentStructures.ParagraphStructure, System.Windows.Documents.DocumentStructures.SectionStructure, System.Windows.Documents.DocumentStructures.StoryFragment, System.Windows.Documents.DocumentStructures.StoryFragments, System.Windows.Documents.DocumentStructures.TableCellStructure, System.Windows.Documents.DocumentStructures.TableRowGroupStructure, System.Windows.Documents.DocumentStructures.TableRowStructure, System.Windows.Documents.DocumentStructures.TableStructure, System.Windows.Documents.PageContentCollection, System.Windows.Documents.TableCellCollection, System.Windows.Documents.TableColumnCollection, System.Windows.Documents.TableRowCollection, System.Windows.Documents.TableRowGroupCollection, System.Windows.Documents.TextElementCollection, System.Windows.Forms.NumericUpDownAccelerationCollection, System.Windows.Markup.INameScopeDictionary, System.Windows.Media.Animation.ClockCollection, System.Windows.Media.Animation.TimelineCollection, System.Windows.Media.CharacterMetricsDictionary, System.Windows.Media.Effects.BitmapEffectCollection, System.Windows.Media.FamilyTypefaceCollection, System.Windows.Media.FontFamilyMapCollection, System.Windows.Media.GeneralTransformCollection, System.Windows.Media.GradientStopCollection, System.Windows.Media.Imaging.BitmapMetadata, System.Windows.Media.LanguageSpecificStringDictionary, System.Windows.Media.Media3D.GeneralTransform3DCollection, System.Windows.Media.Media3D.MaterialCollection, System.Windows.Media.Media3D.Model3DCollection, System.Windows.Media.Media3D.Point3DCollection, System.Windows.Media.Media3D.Transform3DCollection, System.Windows.Media.Media3D.Vector3DCollection, System.Windows.Media.Media3D.Visual3DCollection, System.Windows.Media.PathFigureCollection, System.Windows.Media.PathSegmentCollection, System.Windows.Media.TextEffectCollection, System.Workflow.Activities.OperationParameterInfoCollection, System.Workflow.ComponentModel.ActivityCollection, System.Xml.Xsl.Runtime.XmlQueryNodeSequence, System.Xml.Xsl.Runtime.XmlQuerySequence, ToFrozenDictionary(IEnumerable, Func, IEqualityComparer), ToFrozenDictionary(IEnumerable, Func, Func, IEqualityComparer), ToFrozenSet(IEnumerable, IEqualityComparer), ToFrozenSet(IEnumerable, IEqualityComparer, Boolean), ToImmutableArray(IEnumerable), ToImmutableDictionary(IEnumerable, Func), ToImmutableDictionary(IEnumerable, Func, IEqualityComparer), ToImmutableDictionary(IEnumerable, Func, Func), ToImmutableDictionary(IEnumerable, Func, Func, IEqualityComparer), ToImmutableDictionary(IEnumerable, Tikz: Numbering vertices of regular a-sided Polygon, Word order in a sentence with two clauses. Applies an accumulator function over a sequence. I have IEnumerable list of customerList and index. Is it possible to control it remotely? Computes the sum of the sequence of Double values that are obtained by invoking a transform function on each element of the input sequence. Or use ToList and convert it to List then you can access your value with index: Also if you know the type you can cast your IEnumerable to IList in order to use indexer. In C#, value types can't be null. Thanks for contributing an answer to Stack Overflow! Returns the minimum value in a generic sequence according to a specified key selector function and key comparer. What if you never end up iterating through the IEnumerable at all? A minor scale definition: am I missing something? Invokes a transform function on each element of a sequence and returns the maximum Decimal value. Anonymous types enable the select clause in a LINQ query expression to transform objects of the original sequence into objects whose value and shape may differ from the original. How to combine independent probability distributions? The following example shows how to use an object initializer with a named type, Cat and how to invoke the parameterless constructor. IEnumerable. Enumerates and transforms a sequence, and produces an immutable dictionary of its contents by using the specified key comparer. Can you still use Commanders Strike if the only attack available to forego is an attack against an ally? Generally, the IEnumerable interface will represent an object that can be enumerated and it's a base interface for all non-generic collections that can enumerate. ElementAt checks to see whether the argument is an IList. The . Removes every node in the source collection from its parent node. English version of Russian proverb "The hedgehogs got pricked, cried, but continued to eat the cactus", Embedded hyperlinks in a thesis or research paper. The default equality comparer is used to compare keys. Returns the maximum value in a generic sequence according to a specified key selector function. Why can't the change in a crystal structure be due to the rotation of octahedra? These LINQ methods can be used to extract a single element from an IEnumerable<T> sequence. Only use them if you are absolutely certain that an element exists for them to return. Both variants work with the Dictionary class. For example, if index = 3, it should provide me 3rd item of the IEnumerable . Splits the elements of a sequence into chunks of size at most size. Func, Func, IComparer, IEqualityComparer), ToImmutableSortedSet(IEnumerable), ToImmutableSortedSet(IEnumerable, IComparer), CopyToDataTable(IEnumerable, DataTable, LoadOption), CopyToDataTable(IEnumerable, DataTable, LoadOption, FillErrorEventHandler), Aggregate(IEnumerable, Func), Aggregate(IEnumerable, TAccumulate, Func), Aggregate(IEnumerable, TAccumulate, Func, Func), All(IEnumerable, Func), Any(IEnumerable, Func), Append(IEnumerable, TSource), AsEnumerable(IEnumerable), Average(IEnumerable, Func), Average(IEnumerable, Func), Average(IEnumerable, Func), Average(IEnumerable, Func), Average(IEnumerable, Func>), Average(IEnumerable, Func>), Average(IEnumerable, Func>), Average(IEnumerable, Func>), Average(IEnumerable, Func>), Average(IEnumerable, Func), Chunk(IEnumerable, Int32), Concat(IEnumerable, IEnumerable), Contains(IEnumerable, TSource), Contains(IEnumerable, TSource, IEqualityComparer), Count(IEnumerable, Func), DefaultIfEmpty(IEnumerable), DefaultIfEmpty(IEnumerable, TSource), Distinct(IEnumerable, IEqualityComparer), DistinctBy(IEnumerable, Func), DistinctBy(IEnumerable, Func, IEqualityComparer), ElementAt(IEnumerable, Index), ElementAt(IEnumerable, Int32), ElementAtOrDefault(IEnumerable, Index), ElementAtOrDefault(IEnumerable, Int32), Except(IEnumerable, IEnumerable), Except(IEnumerable, IEnumerable, IEqualityComparer), ExceptBy(IEnumerable, IEnumerable, Func), ExceptBy(IEnumerable, IEnumerable, Func, IEqualityComparer), First(IEnumerable, Func), FirstOrDefault(IEnumerable), FirstOrDefault(IEnumerable, TSource), FirstOrDefault(IEnumerable, Func), FirstOrDefault(IEnumerable, Func, TSource), GroupBy(IEnumerable, Func), GroupBy(IEnumerable, Func, IEqualityComparer), GroupBy(IEnumerable, Func, Func), GroupBy(IEnumerable, Func, Func, IEqualityComparer), GroupBy(IEnumerable, Func, Func,TResult>), GroupBy(IEnumerable, Func, Func,TResult>, IEqualityComparer), GroupBy(IEnumerable, Func, Func, Func,TResult>), GroupBy(IEnumerable, Func Who Is Lori Harvey Biological Dad, Articles H