本文整理汇总了C#中Collection.AddRange方法的典型用法代码示例。如果您正苦于以下问题:C# Collection.AddRange方法的具体用法?C# Collection.AddRange怎么用?C# Collection.AddRange使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Collection
的用法示例。
在下文中一共展示了Collection.AddRange方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: AddRangeTest
public void AddRangeTest()
{
var collection = new Collection<double>();
Assert.DoesNotThrow(() => collection.AddRange(null));
collection.AddRange(new[] {2.0, 3.1});
Assert.AreEqual(2.0, collection[0]);
Assert.AreEqual(3.1, collection[1]);
}
示例2: Load
/// <summary>
/// Loads the Counters.config file, validates it against the XSD schema, and news up the appropriate CounterConfigReader object for each root counter type node.
/// </summary>
/// <param name="hosts">The target hosts to load counters for.</param>
/// <param name="counterLifecycleType">The type of counter to load; e.g. ephemeral or persistent.</param>
/// <returns>Collection of all valid counters in Counters.config across the set of given hosts.</returns>
public static ICollection<ICounter> Load(IEnumerable<Host> hosts, CounterLifecycleType counterLifecycleType)
{
Log.DebugFormat(@"Loading {0} performance counters from {1}..", counterLifecycleType.ToString().ToLowerInvariant(), Path.Combine(Directory.GetCurrentDirectory(), PathToCountersConfig));
var counters = new Collection<ICounter>();
if (loadedConfigDocument == null)
{
loadedConfigDocument = LoadConfig();
}
// Set the root element & begin loading counters.
var documentRoot = loadedConfigDocument.DocumentElement.SelectSingleNode("/Counters");
var counterRootNodes = documentRoot.SelectNodes("child::*");
foreach (XmlNode counterRootNode in counterRootNodes)
{
var counterType = counterRootNode.Name;
Log.DebugFormat("Loading {0} counters..", counterType);
var configReader = CounterConfigReaderFactory.CreateConfigReader(counterType);
foreach (var host in hosts)
{
var countersInNode = configReader.LoadCounters(counterRootNode, host, counterLifecycleType);
if (countersInNode.Count > 0)
{
Log.DebugFormat("Loaded {0} {1} {2} {3} on {4}.",
countersInNode.Count, counterLifecycleType.ToString().ToLowerInvariant(), counterType, "counter".Pluralize(countersInNode.Count), host.Name);
counters.AddRange(countersInNode);
}
}
}
Log.DebugFormat("Successfully loaded {0} {1} from configuration file.", counters.Count, "counter".Pluralize(counters.Count));
return counters;
}
示例3: AddRangeWithNull
public void AddRangeWithNull()
{
// Setup
var collection = new Collection<string>();
// Execute
collection.AddRange(a_items: null);
}
示例4: AddRange_ICollection_Test
public static void AddRange_ICollection_Test()
{
var collection1 = new Collection<string>();
var collection2 = new LinkedList<string>();
collection2.AddFirst("Hello");
collection1.AddRange(collection2);
Assert.That(collection1.Contains("Hello"), Is.True);
}
示例5: CanAddRangeToCollection
public void CanAddRangeToCollection()
{
Collection<object> col = new Collection<object>();
List<object> itemsToAdd = new List<object>{"1", "2"};
col.AddRange(itemsToAdd);
Assert.AreEqual(2, col.Count);
Assert.AreEqual("1", col[0]);
Assert.AreEqual("2", col[1]);
}
示例6: AddRange
public void AddRange()
{
// Setup
var collection = new Collection<string>();
// Execute
collection.AddRange("One", "Two", "Three", "Four");
// Assert
CollectionAssert.AreEquivalent(new[] {"One", "Two", "Three", "Four"}, collection);
}
示例7: AddRangeShouldAllowEmptySequence
public void AddRangeShouldAllowEmptySequence()
{
// arrange
var expected = Enumerable.Empty<object>();
var target = new Collection<object>();
// act
target.AddRange( expected );
// assert
Assert.Equal( 0, target.Count );
}
示例8: AddRangeShouldCopySequence
public void AddRangeShouldCopySequence()
{
// arrange
var expected = new List<object>() { new object(), new object(), new object() };
var target = new Collection<object>();
// act
target.AddRange( expected );
// assert
Assert.Equal( expected.Count, target.Count );
Assert.True( target.SequenceEqual( expected ) );
}
示例9: DataArrivedOnConnection
private void DataArrivedOnConnection(IAsyncResult result)
{
int bytesRead = networkStream.EndRead(result);
Collection<byte> messageBytes = new Collection<byte>();
messageBytes.Add(headerBytes[0]);
Collection<byte> lengthBytes = MqttHeader.ReadLengthBytes(networkStream);
int length = MqttHeader.CalculateLength(lengthBytes);
messageBytes.AddRange<byte>(lengthBytes);
// we've got the bytes that make up the header, inc the size, read the .
var remainingMessage = new byte[length];
int messageBytesRead = networkStream.Read(remainingMessage, 0, length);
if (messageBytesRead < length)
{
// we haven't got all the message, need to figure oput what to do.
}
messageBytes.AddRange<byte>(remainingMessage);
networkStream.BeginRead(headerBytes, 0, 1, DataArrivedOnConnection, null);
}
示例10: Load
/// <summary>
/// Loads the Counters.config file, validates it against the XSD schema, and news up the appropriate CounterConfigReader object for each root counter type node.
/// </summary>
/// <param name="pathToConfig">The path to the Counters.config file.</param>
/// <param name="hosts">The target hosts to load counters for.</param>
/// <returns>Collection of all valid counters in Counters.config across the set of given hosts.</returns>
public static ICollection<ICounter> Load(string pathToConfig, IEnumerable<Host> hosts)
{
var counters = new Collection<ICounter>();
// Load the document & validate against internal schema.
var settings = new XmlReaderSettings
{
ValidationType = ValidationType.Schema
};
var doc = new XmlDocument();
try
{
settings.Schemas.Add("", PathToSchema);
var reader = XmlReader.Create(pathToConfig, settings);
doc.Load(reader);
}
catch (FileNotFoundException ex)
{
throw new ConfigurationErrorsException(String.Format("Could not find file '{0}'.", ex.Message));
}
catch (XmlException ex)
{
throw new ConfigurationErrorsException(String.Format("Malformed XML in' {0}': {1}", pathToConfig, ex.Message));
}
catch (XmlSchemaValidationException ex)
{
throw new ConfigurationErrorsException(String.Format("Failed to validate '{0}': {1} (Line {2})", pathToConfig, ex.Message, ex.LineNumber));
}
Log.Debug(String.Format("Successfully validated '{0}' against '{1}'.", pathToConfig, PathToSchema));
// Set the root element & begin loading counters.
var documentRoot = doc.DocumentElement.SelectSingleNode("/Counters");
var counterRootNodes = documentRoot.SelectNodes("child::*");
foreach (XmlNode counterRootNode in counterRootNodes)
{
var counterType = counterRootNode.Name;
Log.Debug(String.Format("Loading {0} counters..", counterType));
var configReader = CounterConfigReaderFactory.CreateConfigReader(counterType);
foreach (var host in hosts)
{
var countersInNode = configReader.LoadCounters(counterRootNode, host);
Log.Info(String.Format("Loaded {0} {1} {2} on {3}.", countersInNode.Count, counterType, "counter".Pluralize(countersInNode.Count), host.Name));
counters.AddRange(countersInNode);
}
}
return counters;
}
示例11: CreateSearchRequest
protected override SearchUsagesRequest CreateSearchRequest(IDataContext dataContext, IDeclaredElement declaredElement, IDeclaredElement initialTarget)
{
// do not call the base implementation : we are going to override it completely, by mimicking most of its behavior. see comments below.
SearchUsagesRequest specialUsagesRequest = this.TryFindSpecialUsagesRequest(dataContext);
if (specialUsagesRequest != null)
return specialUsagesRequest;
var elementsToSearch = new Collection<IDeclaredElement> { declaredElement };
// sole addition to the base method implementation
var additionalElementsToSearch = this.GetAdditionalElementsToSearch(dataContext);
elementsToSearch.AddRange(additionalElementsToSearch);
const SearchPattern SearchPattern = SearchPattern.FIND_USAGES | SearchPattern.FIND_IMPLEMENTORS_USAGES | SearchPattern.FIND_LATEBOUND_REFERENCES;
var searchDomain = SearchDomainContextUtil.GetSearchDomainContext(dataContext).GetDefaultDomain().SearchDomain;
var declaredElements = new[] { initialTarget };
var searchUsagesRequest = (SearchUsagesRequest)new SearchDeclaredElementUsagesRequest(elementsToSearch, SearchPattern, searchDomain, declaredElements);
return searchUsagesRequest;
}
示例12: ThrowsArgumentNullExceptionForNullRange
public void ThrowsArgumentNullExceptionForNullRange()
{
var collection = new Collection<int> { 1, 2, 3 };
ExceptionTester.CallMethodAndExpectException<ArgumentNullException>(() => collection.AddRange(null));
}
示例13: ClearTestEntities
private void ClearTestEntities()
{
Type[] types = new Type[] {
typeof(TestArticle),
typeof(TestCategory),
typeof(TestUser),
typeof(TestRole),
typeof(EntityOne),
typeof(EntityTwo),
typeof(TestEntity), typeof(EntityThree), typeof(EntityFour) };
Collection<IEntity> entities = new Collection<IEntity>();
foreach (Type type in types)
entities.AddRange((IEntity[])DataAccess.Data.Indexer.GetEntities(type));
foreach (IEntity entity in entities)
{
DataAccess.Data.Deleter.Delete(entity);
}
string[] referenceStoreNames = new String[]{
DataUtilities.GetDataStoreName("TestArticle", "TestCategory"),
DataUtilities.GetDataStoreName("TestUser", "TestRole")
};
foreach (string storeName in referenceStoreNames)
{
foreach (IEntity entity in DataAccess.Data.Stores[storeName].Indexer.GetEntities<EntityReference>())
{
DataAccess.Data.Stores[storeName].Deleter.Delete(entity);
}
}
}
示例14: GetAdditionalElementsToSearch
protected ICollection<IDeclaredElement> GetAdditionalElementsToSearch(IDataContext context)
{
var selectedConstructorDeclaration = context.GetSelectedTreeNode<IConstructorDeclaration>();
if (selectedConstructorDeclaration != null)
{
var selectedTypeDeclaration = selectedConstructorDeclaration.GetContainingTypeDeclaration();
if (selectedTypeDeclaration != null)
{
ISearchDomain searchDomain = SearchDomainFactory.Instance.CreateSearchDomain(selectedTypeDeclaration.GetPsiModule().GetSolution(), false);
var referencesToSelectedType = selectedTypeDeclaration
.GetPsiServices()
.Finder
.FindReferences(selectedTypeDeclaration.DeclaredElement, searchDomain, NullProgressIndicator.Instance);
var referencesToSelectedTypeExpressions = referencesToSelectedType
.Select(o => o.GetTreeNode().GetContainingNode<IReferenceExpression>())
.Where(o => o != null);
var createMethods = new Collection<IDeclaredElement>();
foreach (var referenceExpression in referencesToSelectedTypeExpressions)
{
var creatingFactory = ((IReferenceExpression)referenceExpression.FirstChild.FirstChild)
.TypeArgumentList
.TypeArguments[0];
// Find all the calls to IxxxFactory.Create()
var factoryInterface = ((Interface)creatingFactory.GetScalarType().Resolve().DeclaredElement);
Func<IDeclaredType, IList<IDeclaredType>> recursionForFindingAllSuperTypes = null;
recursionForFindingAllSuperTypes = type =>
{
var ancestorDirectSuperTypes = new List<IDeclaredType>();
foreach (var ancestor in type.GetSuperTypes())
{
IEnumerable<IDeclaredType> superTypes = recursionForFindingAllSuperTypes(ancestor);
ancestorDirectSuperTypes.AddRange(superTypes);
}
return ancestorDirectSuperTypes;
};
var allSuperclasses = factoryInterface.GetAllSuperTypes();
IEnumerable<IMethod> allMethods = allSuperclasses
.Where(o => o.GetClrName().FullName != typeof(Object).FullName)
.Select(o => o.GetScalarType().GetTypeElement())
.SelectMany(o => o.Methods)
.Concat(factoryInterface.Methods);
// FIXME : we are only handling the methods of the interface, not the inherited methods !
var createMethodsForReference =
allMethods.Where(
o =>
{
var substitutions = allSuperclasses
.Select(x => x.GetSubstitution())
.Where(s => s.Domain.Count > 0);
var hasGenericSuperType = substitutions.Any();
// todo : we still have to make sure we only keep the typeParameters which are compatible with the selected .ctor.
IEnumerable<IType> typeParameters = substitutions
.SelectMany(x => x.Domain, (singleSubstitution, typeParameter) => singleSubstitution[typeParameter])
.Where(x => x != null);
var typeReturnedByMethodOfFactory = o.ReturnType.GetScalarType().GetTypeElement();
var isDescendant = selectedTypeDeclaration.DeclaredElement.IsDescendantOf(typeReturnedByMethodOfFactory);
if (hasGenericSuperType)
{
// if we have a generic factory interface : let's check if one of the type arguments do match the output value of a method.
isDescendant = selectedTypeDeclaration.DeclaredElement.GetAllSuperTypes().Union(typeParameters).Any();
}
return isDescendant;
})
.SelectMany(o => o.GetDeclarations(), (method, declaration) => declaration.DeclaredElement);
createMethods.AddRange(createMethodsForReference);
}
return createMethods;
}
}
return new IDeclaredElement[0];
}
示例15: GetPackagedModules
/// <summary>
/// Gets the available latest version of packaged modules removing.
/// </summary>
/// <summary>
/// Gets the packaged modules from the repository.
/// </summary>
/// <returns>
/// The packaged modules
/// </returns>
private IEnumerable<ModuleInfo> GetPackagedModules()
{
IPackageRepository packageRepository = GetPackageRepository();
IQueryable<IPackage> queryablePackages = packageRepository.GetPackages();
Expression<Func<IPackage, bool>> filterExpression;
if (!string.IsNullOrWhiteSpace(PackagedModuleIdFilterExpression))
{
filterExpression = package => (package.Id.Contains(PackagedModuleIdFilterExpression) && package.Description != null && package.Description.StartsWith("ModuleName") && package.Description.Contains("ModuleType"));
}
else
{
filterExpression = package => (package.Description != null && package.Description.StartsWith("ModuleName") && package.Description.Contains("ModuleType"));
}
IEnumerable<IPackage> packages = queryablePackages.Where(filterExpression).ToList().GroupBy(package => package.Id).Select(packageGroup => packageGroup.ToList().OrderByDescending(package => package.Version).FirstOrDefault()).Where(package => package != null).ToList();
var moduleInfos = new List<ModuleInfo>();
foreach (var package in packages)
{
var match = ModuleDescriptorRegex.Match(package.Description);
if (match.Success)
{
var moduleName = match.Groups[1].Value.Trim();
var moduleType = match.Groups[2].Value.Trim();
if (!string.IsNullOrWhiteSpace(moduleName) && !string.IsNullOrWhiteSpace(moduleType))
{
var @ref = string.Format(CultureInfo.InvariantCulture, "{0}, {1}", package.Id, package.Version);
var key = string.Format(CultureInfo.InvariantCulture, "ModuleName:{0}; ModuleType:{1}; Ref:{2}; Version:{3}", moduleName, moduleType, @ref, package.Version);
var dependsOn = new Collection<string>();
if (match.Groups.Count == 5)
{
string dependencies = match.Groups[4].Value.Trim();
if (!string.IsNullOrWhiteSpace(dependencies))
{
dependsOn.AddRange(dependencies.Split(',').Select(dependency => dependency.Trim()));
}
}
moduleInfos.Add(_moduleInfoCacheStoreCacheStorage.GetFromCacheOrFetch(key, () => new ModuleInfo(moduleName, moduleType) { Ref = @ref, InitializationMode = InitializationMode.OnDemand, DependsOn = dependsOn }));
}
}
}
return moduleInfos;
}