本文整理汇总了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;
}
示例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;
}
示例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)));
}
}
示例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];
}
示例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;
}
示例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());
}
}
示例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);
});
}
示例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();
}
示例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);
}
}
示例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;
}
示例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;
}
示例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;
}
示例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;
}
示例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();
}
示例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);
}
}