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


C# IEnumerable.Distinct方法代码示例

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


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

示例1: GetAllLayers

 protected IEnumerable<ModelApplicationBase> GetAllLayers(IEnumerable<ModelDifferenceObject> differenceObjects, ModelApplicationBase master) {
     if (GetttingNonAppModels(differenceObjects))
         differenceObjects = differenceObjects.Where(o => o.CombineOrder < CombineOrder);
     var modelApplicationBases = differenceObjects.Distinct().Select(differenceObject => differenceObject.GetModel(master));
     modelApplicationBases = modelApplicationBases.Concat(new List<ModelApplicationBase> { GetModel(master) });
     return modelApplicationBases;
 }
开发者ID:gvilas,项目名称:eXpand,代码行数:7,代码来源:ModelDifferenceObject.cs

示例2: ValidateFields

        private string[] ValidateFields(string indexName, IEnumerable<string> indexFields)
        {
            var withoutDuplicates = indexFields.Distinct().ToArray();

            var members = _reflectionService.GetFieldsAndProperties(_classInfo.UnderlyingType);

            foreach (var indexField in withoutDuplicates)
            {
                var memberInfo = members.FirstOrDefault(x => x.Name.Equals(indexField));

                var memberType = memberInfo is PropertyInfo
                                     ? ((PropertyInfo) memberInfo).PropertyType
                                     : ((FieldInfo) memberInfo).FieldType;

                if (memberInfo != null && (typeof(IComparable)).IsAssignableFrom(memberType)) 
                    continue;

                var fieldType = (memberInfo == null || memberInfo.DeclaringType == null)
                                    ? "Field doesn't exist"
                                    : memberType.FullName;

                throw new OdbRuntimeException(NDatabaseError.IndexKeysMustImplementComparable.AddParameter(indexName)
                                                            .AddParameter(indexField)
                                                            .AddParameter(fieldType));
            }

            return withoutDuplicates;
        }
开发者ID:spolnik,项目名称:ndatabase,代码行数:28,代码来源:IndexManager.cs

示例3: ParseText

        public static IEnumerable<TextEntityDescription> ParseText(
            string text, IEnumerable<TwitterEntity> entities)
        {
            if (entities == null) throw new ArgumentNullException("entities");
            var escaped = ParsingExtension.EscapeEntity(text);
            var endIndex = 0;

            // distinct by startindex ignores extended_entities.
            foreach (var entity in entities.Distinct(e => e.StartIndex).OrderBy(e => e.StartIndex))
            {
                if (endIndex < entity.StartIndex)
                {
                    // return raw string
                    yield return new TextEntityDescription(ParsingExtension.ResolveEntity(
                        escaped.SubstringForSurrogatePaire(endIndex, entity.StartIndex - endIndex)));
                }
                // get entitied text
                var body = ParsingExtension.ResolveEntity(escaped.SubstringForSurrogatePaire(
                    entity.StartIndex, entity.EndIndex - entity.StartIndex));
                yield return new TextEntityDescription(body, entity);
                endIndex = entity.EndIndex;
            }
            if (endIndex == 0)
            {
                // entity is empty.
                yield return new TextEntityDescription(text);
            }
            else if (endIndex < escaped.Length)
            {
                // return remain text
                yield return new TextEntityDescription(ParsingExtension.ResolveEntity(
                    escaped.SubstringForSurrogatePaire(endIndex)));
            }
        }
开发者ID:WizFox,项目名称:StarryEyes,代码行数:34,代码来源:TextEntityResolver.cs

示例4: TariffRestriction

        /// <summary>
        /// Create a new tariff restrictions class.
        /// </summary>
        /// <param name="Time">Start/end time of day, for example "13:30 - 19:45", valid from this time of the day.</param>
        /// <param name="Date">Start/end date, for example: 2015-12-24, valid from this day until that day (excluding that day).</param>
        /// <param name="kWh">Minimum/Maximum used energy in kWh, for example 20, valid from this amount of energy is used.</param>
        /// <param name="Power">Minimum/Maximum power in kW, for example 0, valid from this charging speed.</param>
        /// <param name="Duration">Minimum/Maximum duration in seconds, valid for a duration from x seconds.</param>
        /// <param name="DayOfWeek">Minimum/Maximum duration in seconds, valid for a duration from x seconds.</param>
        public TariffRestriction(TimeRange?              Time       = null,
                                 StartEndDateTime?       Date       = null,
                                 DecimalMinMax?          kWh        = null,
                                 DecimalMinMax?          Power      = null,
                                 TimeSpanMinMax?         Duration   = null,
                                 IEnumerable<DayOfWeek>  DayOfWeek  = null)
        {
            #region Initial checks

            if (!Time.   HasValue &&
                !Date.   HasValue &&
                !kWh.    HasValue &&
                Power.   HasValue &&
                Duration.HasValue &&
                DayOfWeek == null)
                throw new ArgumentNullException("All given parameter equals null is invalid!");

            #endregion

            this.Time       = Time;
            this.Date       = Date;
            this.kWh        = kWh;
            this.Power      = Power;
            this.Duration   = Duration;
            this.DayOfWeek  = DayOfWeek != null ? DayOfWeek.Distinct() : new DayOfWeek[0];
        }
开发者ID:OpenChargingCloud,项目名称:WWCP_OCPI,代码行数:35,代码来源:TariffRestrictions.cs

示例5: SetDestinations

        /// <summary>
        /// Adds specific destinations to a claim.
        /// </summary>
        /// <param name="claim">The <see cref="Claim"/> instance.</param>
        /// <param name="destinations">The destinations.</param>
        public static Claim SetDestinations(this Claim claim, IEnumerable<string> destinations)
        {
            if (claim == null)
            {
                throw new ArgumentNullException(nameof(claim));
            }

            if (destinations == null || !destinations.Any())
            {
                claim.Properties.Remove(Properties.Destinations);

                return claim;
            }

            if (destinations.Any(destination => destination.Contains(" ")))
            {
                throw new ArgumentException("Destinations cannot contain spaces.", nameof(destinations));
            }

            //claim.Properties[Properties.Destinations] =
            //    string.Join(" ", destinations.Distinct(StringComparer.Ordinal));
            //TODO chage destination with destinations in rc 2
            claim.Properties[Properties.Destination] =
                string.Join(" ", destinations.Distinct(StringComparer.Ordinal));

            return claim;
        }
开发者ID:Stalso,项目名称:AspNetTemplate,代码行数:32,代码来源:ClaimExtensions.cs

示例6: ValidateOperators

        private void ValidateOperators(IEnumerable<IOperator> operatorList)
        {
            var codes = operatorList.Select(op => op.Code).ToList();
            var duplicateCodes = operatorList.Count() != operatorList.Distinct().Count();

            if (duplicateCodes) {
                var groupedCodes = operatorList.GroupBy(x => x.Code);
                var moreThanOneCodeGroups = groupedCodes.Where(x => x.Count() > 1);

                var sb = new StringBuilder();
                sb.AppendLine("Operators contain duplicate codes:");

                foreach (var group in moreThanOneCodeGroups) {
                    var groupString = string.Format("\\tThe code {0} is present {1} times in operators {2}", group.Key, group.Count(), string.Join(", ", group.Select(x => x.GetType().Name)));
                    sb.AppendLine(groupString);
                }

                throw new ArgumentException(sb.ToString());
            }

            if (codes.Any(x => string.IsNullOrWhiteSpace(x))) {
                var whitespaceCodes = operatorList.Where(x => string.IsNullOrWhiteSpace(x.Code));

                var sb = new StringBuilder();
                sb.AppendLine("Operators contain empty codes:");

                foreach (var op in whitespaceCodes) {
                    var groupString = string.Format("\\tThe code of {0} is empty", op.GetType().Name);
                    sb.AppendLine(groupString);
                }

                throw new ArgumentException(sb.ToString());
            }
        }
开发者ID:taneltumanski,项目名称:WebCalculator,代码行数:34,代码来源:OperatorFactory.cs

示例7: TagAsync

        /// <summary>
        /// Set tags to the specified <paramref name="file"/>.
        /// </summary>
        /// <returns>The task to process it.</returns>
        /// <param name="file">File to tag.</param>
        /// <param name="tags">Tags to set.</param>
        /// <param name="clear">If set to <c>true</c> replace existing tags with ne <paramref name="tags"/>.</param>
        public Task TagAsync(FileInfo file, IEnumerable<string> tags, bool clear)
        {
            return Task.Factory.StartNew(() =>
            {
                ImageFile imagefile = ImageFile.FromFile(file.FullName);

                string tagsValue;
                if (clear)
                {
                    tagsValue = tags.Distinct(StringComparer.CurrentCultureIgnoreCase).Join(";");
                }
                else
                {
                    List<string> existingTags = new List<string>();
                    ExifProperty existingTagsValue;
                    if (imagefile.Properties.TryGetValue(ExifTag.WindowsKeywords, out existingTagsValue))
                        existingTags = existingTagsValue.Value.ToString().Split(';').ToList();
                    tagsValue = tags.Union(existingTags).Distinct(StringComparer.CurrentCultureIgnoreCase).Join(";");
                }

                imagefile.Properties.Set(ExifTag.WindowsKeywords, tagsValue);

                imagefile.Save(file.FullName);
            });
        }
开发者ID:crabouif,项目名称:Self-Media-Database,代码行数:32,代码来源:FileSystemImageManager.cs

示例8: SaveToCache

        public static void SaveToCache(TwitterResource resource, IEnumerable<TwitterStatus> list)
        {
            string fileName = GetCacheName(resource);

            var serializer = new SharpSerializer(SerializerSettings);
            Mutex mutex = new Mutex(false, "OCELL_FILE_MUTEX" + fileName);

            if (mutex.WaitOne(1000))
            {
                try
                {
                    using (var stream = FileAbstractor.GetFileStream(fileName))
                    {
                        serializer.Serialize(list.Distinct().OfType<TwitterStatus>().ToList(), stream);
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex);
                }
                finally
                {
                    mutex.ReleaseMutex();
                }
            }

            mutex.Dispose();
        }
开发者ID:Quertz,项目名称:Ocell,代码行数:28,代码来源:Cacher.cs

示例9: LogImportedDefaultGroups

		private static void LogImportedDefaultGroups(IEnumerable<AuthorityGroupDefinition> groups)
		{
			foreach (var g in groups.Distinct())
			{
				Platform.Log(LogLevel.Info, "Imported default authority group definition: {0}", g.Name);
			}
		}
开发者ID:nhannd,项目名称:Xian,代码行数:7,代码来源:SetupHelper.cs

示例10: ScriptResult

        public ScriptResult(
            object returnValue = null,
            Exception executionException = null,
            Exception compilationException = null, 
            IEnumerable<string> invalidNamespaces = null)
        {
            if (returnValue != null)
            {
                ReturnValue = returnValue;
            }

            if (executionException != null)
            {
                ExecuteExceptionInfo = ExceptionDispatchInfo.Capture(executionException);
            }

            if (compilationException != null)
            {
                CompileExceptionInfo = ExceptionDispatchInfo.Capture(compilationException);
            }

            if (invalidNamespaces != null)
            {
                foreach (var ns in invalidNamespaces.Distinct())
                {
                    _invalidNamespaces.Add(ns);
                }
            }

            IsCompleteSubmission = true;
        }
开发者ID:AsCloud,项目名称:scriptcs,代码行数:31,代码来源:ScriptResult.cs

示例11: ServerMultiBinding

 /// <summary>
 /// Initializes a new instance of the <see cref="ServerMultiBinding"/> class.
 /// </summary>
 /// <param name="subBindings">The sub bindings.</param>
 /// <param name="readOnly">if set to <c>true</c> [read only].</param>
 public ServerMultiBinding(IEnumerable<IServerBinding> subBindings, bool readOnly = false)
 {
     Condition.Requires(subBindings, "subBindings").IsNotNull();
     _SubBindings = subBindings.Distinct(new UriEqualityComparer<IServerBinding>()).ToList();
     Condition.Requires(_SubBindings, "SubBindings").IsLongerThan(1,"Must have more than one unique server binding.");
     ReadOnly = readOnly;
 }
开发者ID:automatonic,项目名称:mongodb-net,代码行数:12,代码来源:ServerMultiBinding.cs

示例12: GetMaxClusters

        public static int GetMaxClusters(IEnumerable<int> numbers, int bits, int maxSpacing)
        {
            var distinctNumbers = numbers.Distinct().ToArray();
            int clusterCount = distinctNumbers.Length;
            var numberToCluster = new Dictionary<int, int>();

            for (int i = 0; i < clusterCount; i++)
            {
                numberToCluster.Add(distinctNumbers[i], i);
            }

            var unionFind = new UnionFind(clusterCount);
            for (int spacing = 1; spacing <= maxSpacing; spacing++)
            {
                foreach (var number in distinctNumbers)
                {
                    var modifications = GetModifications(number, bits, spacing, 0).ToArray();
                    foreach (var modification in modifications.Where(numberToCluster.ContainsKey))
                    {
                        var cluster1 = unionFind.Find(numberToCluster[number]);
                        var cluster2 = unionFind.Find(numberToCluster[modification]);
                        if (cluster1 != cluster2)
                        {
                            unionFind.Union(cluster1, cluster2);
                            clusterCount--;
                        }
                    }
                }
            }

            return clusterCount;
        }
开发者ID:korzenikov,项目名称:Projects,代码行数:32,代码来源:Clustering.cs

示例13: LoadTweets

        public static IReadOnlyCollection<PoliticalTweet> LoadTweets( IEnumerable<string> handles )
        {
            var service = new TwitterService( ConsumerKey, ConsumerSecret );
            service.AuthenticateWith( AccessToken, AccessTokenSecret );
            var results = new List<PoliticalTweet>();

            foreach ( var handle in handles.Distinct() )
            {
                try
                {
                    var response = service.ListTweetsOnUserTimeline( new ListTweetsOnUserTimelineOptions
                    {
                        ScreenName = handle,
                        Count = 200,
                        IncludeRts = false,
                        ExcludeReplies = true
                    } );
                    results.AddRange( response.Select( t => new PoliticalTweet( handle, t.Text, t.CreatedDate, t.IdStr ) ) );

                    Debug.WriteLine( $"{service.Response.RateLimitStatus.RemainingHits} remaining hits." );
                    if ( service.Response.RateLimitStatus.RemainingHits <= 0 )
                    {
                        var wait = service.Response.RateLimitStatus.ResetTime.ToUniversalTime() - DateTime.UtcNow;
                        Debug.WriteLine( $"Rate limit reached. Sleeping for {wait}." );
                        Thread.Sleep( wait );
                    }
                }
                catch
                {
                    Debug.WriteLine( $"Skipping {handle}" );
                }
            }

            return results;
        }
开发者ID:PoliTweets,项目名称:importer,代码行数:35,代码来源:TweetsImporter.cs

示例14: TypeCoupling

		public TypeCoupling(string typeName, string namespaceName, string assemblyName, IEnumerable<string> usedMethods, IEnumerable<string> usedProperties, IEnumerable<string> useEvents)
			: base(typeName, namespaceName, assemblyName)
		{
			UsedMethods = usedMethods.Distinct().AsArray();
			UsedProperties = usedProperties.Distinct().AsArray();
			UsedEvents = useEvents.Distinct().AsArray();
		}
开发者ID:henrylle,项目名称:ArchiMetrics,代码行数:7,代码来源:TypeCoupling.cs

示例15: RepoConfig

        internal RepoConfig(
            IEnumerable<NuGetPackage> fixedPackages, 
            IEnumerable<string> toolsetPackages, 
            IEnumerable<Regex> nuspecExcludes,
            IEnumerable<Regex> projectJsonExcludes,
            GenerateData? msbuildGenerateData)
        {
            Debug.Assert(toolsetPackages.Distinct().Count() == toolsetPackages.Count());
            MSBuildGenerateData = msbuildGenerateData;
            FixedPackages = fixedPackages.OrderBy(x => x.Name).ToImmutableArray();
            NuSpecExcludes = nuspecExcludes.ToImmutableArray();
            ProjectJsonExcludes = projectJsonExcludes.ToImmutableArray();
            ToolsetPackages = toolsetPackages.OrderBy(x => x).ToImmutableArray();

            var map = new Dictionary<string, List<string>>();
            foreach (var nugetRef in fixedPackages)
            {
                List<string> list;
                if (!map.TryGetValue(nugetRef.Name, out list))
                {
                    list = new List<string>(capacity: 1);
                    map[nugetRef.Name] = list;
                }

                list.Add(nugetRef.Version);
            }
        }
开发者ID:XieShuquan,项目名称:roslyn,代码行数:27,代码来源:RepoConfig.cs


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