本文整理汇总了C#中Collection.Select方法的典型用法代码示例。如果您正苦于以下问题:C# Collection.Select方法的具体用法?C# Collection.Select怎么用?C# Collection.Select使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Collection
的用法示例。
在下文中一共展示了Collection.Select方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Execute
/// <summary>
/// Executes a powershell script
/// </summary>
/// <param name="folder">Folder where to execute the script</param>
/// <param name="file">Script to execute</param>
/// <param name="configuration">Configuration used</param>
/// <param name="log">Logger to use</param>
/// <param name="parameters">Parameters for the script</param>
public static void Execute(string folder, string file, string configuration, ILogger log, Dictionary<string, string> parameters)
{
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
Runspace runspace = RunspaceFactory.CreateRunspace(new Host(), runspaceConfiguration);
runspace.Open();
runspace.SessionStateProxy.Path.SetLocation(folder);
RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted");
Pipeline pipeline = runspace.CreatePipeline();
Command myCommand = new Command(Path.Combine(folder, file));
foreach (var param in parameters.Keys)
{
myCommand.Parameters.Add(new CommandParameter("-" + param, parameters[param]));
}
myCommand.Parameters.Add(new CommandParameter("-Verb", "RunAs"));
pipeline.Commands.Add(myCommand);
Collection<PSObject> results = new Collection<PSObject>();
try
{
results = pipeline.Invoke();
}
catch (RuntimeException e)
{
log.Log(String.Join("\r\n", results.Select(x => x.ToString())) + "\r\n" + e.Message.ToString(), true);
return;
}
log.Log(String.Join("\r\n", results.Select(x => x.ToString())), pipeline.Error.Count > 0);
}
示例2: AlreadyContainsCheck
static bool AlreadyContainsCheck(Collection<Instruction> instructions)
{
return instructions
.Select(instruction => instruction.Operand)
.OfType<MethodReference>()
.Any(operand => operand.Name == "CheckIsFrozen");
}
示例3: PromptForChoice
public override int PromptForChoice(
string promptCaption,
string promptMessage,
Collection<ChoiceDescription> choiceDescriptions,
int defaultChoice)
{
Task<int> promptTask =
this.consoleHost
.PromptForChoice(
promptCaption,
promptMessage,
choiceDescriptions.Select(ChoiceDetails.Create),
defaultChoice);
// This will synchronously block on the async PromptForChoice
// method (which ultimately gets run on another thread) and
// then returns the result of the method.
int choiceResult = promptTask.Result;
// Check for errors
if (promptTask.Status == TaskStatus.Faulted)
{
// Rethrow the exception
throw new Exception(
"PromptForChoice failed, check inner exception for details",
promptTask.Exception);
}
// Return the result
return choiceResult;
}
示例4: AddAndCleanWebConfigModification
/// <summary>
/// Method to add one or multiple WebConfig modifications
/// NOTE: There should not have 2 modifications with the same Owner.
/// </summary>
/// <param name="webApp">The current Web Application</param>
/// <param name="webConfigModificationCollection">The collection of WebConfig modifications to remove-and-add</param>
/// <remarks>All SPWebConfigModification Owner should be UNIQUE !</remarks>
public void AddAndCleanWebConfigModification(SPWebApplication webApp, Collection<SPWebConfigModification> webConfigModificationCollection)
{
// Verify emptyness
if (webConfigModificationCollection == null || !webConfigModificationCollection.Any())
{
throw new ArgumentNullException("webConfigModificationCollection");
}
SPWebApplication webApplication = SPWebService.ContentService.WebApplications[webApp.Id];
// Start by cleaning up any existing modification for all owners
// By Good practice, owners should be unique, so we do this to remove duplicates entries if any.
var owners = webConfigModificationCollection.Select(modif => modif.Owner).Distinct().ToList();
this.RemoveExistingModificationsFromOwner(webApplication, owners);
// Add WebConfig modifications
foreach (var webConfigModification in webConfigModificationCollection)
{
webApplication.WebConfigModifications.Add(webConfigModification);
}
// Commit modification additions to the specified web application
webApplication.Update();
// Push modifications through the farm
webApplication.WebService.ApplyWebConfigModifications();
// Wait for timer job
WaitForWebConfigPropagation(webApplication.Farm);
}
示例5: Add_AddsItemToData_IfPatternIsSet
public void Add_AddsItemToData_IfPatternIsSet()
{
var data = new Collection<PatternData>();
var model = new PatternCollectionViewModel(data);
model.Values.Add(new PatternViewModel("x"));
Assert.Equal(new[] { "x" }, data.Select(p => p.Regex.ToString()));
}
示例6: AddAndCleanWebConfigModification
/// <summary>
/// Method to add one or multiple WebConfig modifications
/// NOTE: There should not have 2 modifications with the same Owner.
/// </summary>
/// <param name="web">The current Web Application</param>
/// <param name="webConfigModificationCollection">The collection of WebConfig modifications to remove-and-add</param>
/// <remarks>All SPWebConfigModification Owner should be UNIQUE !</remarks>
public void AddAndCleanWebConfigModification(SPWebApplication webApp, Collection<SPWebConfigModification> webConfigModificationCollection)
{
// Verify emptyness
if (webConfigModificationCollection == null || !webConfigModificationCollection.Any())
{
throw new ArgumentNullException("webConfigModificationCollection");
}
SPWebApplication webApplication = SPWebService.ContentService.WebApplications[webApp.Id];
// Start by cleaning up any existing modification for all owners
foreach (var owner in webConfigModificationCollection.Select(modif => modif.Owner).Distinct())
{
// Remove all modification by the same owner.
// By Good practice, owner should be unique, so we do this to remove duplicates entries if any.
this.RemoveExistingModificationsFromOwner(webApplication, owner);
}
if (webApplication.Farm.TimerService.Instances.Count > 1)
{
// HACK:
//
// When there are multiple front-end Web servers in the
// SharePoint farm, we need to wait for the timer job that
// performs the Web.config modifications to complete before
// continuing. Otherwise, we may encounter the following error
// (e.g. when applying Web.config changes from two different
// features in rapid succession):
//
// "A web configuration modification operation is already
// running."
WaitForOnetimeJobToFinish(
webApplication.Farm,
"Microsoft SharePoint Foundation Web.Config Update",
120);
}
// Add WebConfig modifications
foreach (var webConfigModification in webConfigModificationCollection)
{
webApplication.WebConfigModifications.Add(webConfigModification);
}
// Commit modification additions to the specified web application
webApplication.Update();
// Push modifications through the farm
webApplication.WebService.ApplyWebConfigModifications();
if (webApplication.Farm.TimerService.Instances.Count > 1)
{
WaitForOnetimeJobToFinish(
webApplication.Farm,
"Microsoft SharePoint Foundation Web.Config Update",
120);
}
}
示例7: PatternChange_AddsItemToData_IfPatternIsSet
public void PatternChange_AddsItemToData_IfPatternIsSet()
{
var data = new Collection<PatternData>();
var model = new PatternCollectionViewModel(data);
var pattern = new PatternViewModel("");
model.Values.Add(pattern);
pattern.Pattern.Value = "x";
Assert.Equal(new[] { "x" }, data.Select(p => p.Regex.ToString()));
}
示例8: PromptForChoice
public override int PromptForChoice(
string promptCaption,
string promptMessage,
Collection<ChoiceDescription> choiceDescriptions,
int defaultChoice)
{
if (this.consoleHost != null)
{
ChoiceDetails[] choices =
choiceDescriptions
.Select(ChoiceDetails.Create)
.ToArray();
Task<int> promptTask =
this.consoleHost
.GetChoicePromptHandler()
.PromptForChoice(
promptCaption,
promptMessage,
choices,
defaultChoice);
// This will synchronously block on the async PromptForChoice
// method (which ultimately gets run on another thread) and
// then returns the result of the method.
int choiceResult = promptTask.Result;
// Check for errors
if (promptTask.Status == TaskStatus.Faulted)
{
// Rethrow the exception
throw new Exception(
"PromptForChoice failed, check inner exception for details",
promptTask.Exception);
}
else if (promptTask.Result == -1)
{
// Stop the pipeline if the prompt was cancelled
throw new PipelineStoppedException();
}
// Return the result
return choiceResult;
}
else
{
// Notify the caller that there's no implementation
throw new NotImplementedException();
}
}
示例9: Paste
/// <summary>
/// Paste items from clipboard into the designer.
/// </summary>
public void Paste()
{
bool pasted = false;
string combinedXaml = Clipboard.GetText(TextDataFormat.Xaml);
IEnumerable<string> xamls = combinedXaml.Split(_delimeter);
xamls = xamls.Where(xaml => xaml != "");
DesignItem parent = _context.Services.Selection.PrimarySelection;
DesignItem child = _context.Services.Selection.PrimarySelection;
XamlDesignItem rootItem = _context.RootItem as XamlDesignItem;
var pastedItems = new Collection<DesignItem>();
foreach(var xaml in xamls) {
var obj = XamlParser.ParseSnippet(rootItem.XamlObject, xaml, _settings);
if(obj!=null) {
DesignItem item = _context._componentService.RegisterXamlComponentRecursive(obj);
if (item != null)
pastedItems.Add(item);
}
}
if (pastedItems.Count != 0) {
var changeGroup = _context.OpenGroup("Paste " + pastedItems.Count + " elements", pastedItems);
while (parent != null && pasted == false) {
if (parent.ContentProperty != null) {
if (parent.ContentProperty.IsCollection) {
if (CollectionSupport.CanCollectionAdd(parent.ContentProperty.ReturnType, pastedItems.Select(item => item.Component)) && parent.GetBehavior<IPlacementBehavior>()!=null) {
AddInParent(parent, pastedItems);
pasted = true;
}
} else if (pastedItems.Count == 1 && parent.ContentProperty.Value == null && parent.ContentProperty.ValueOnInstance == null && DefaultPlacementBehavior.CanContentControlAdd((ContentControl)parent.View)) {
AddInParent(parent, pastedItems);
pasted = true;
}
if(!pasted)
parent=parent.Parent;
} else {
parent = parent.Parent;
}
}
while (pasted == false) {
if (child.ContentProperty != null) {
if (child.ContentProperty.IsCollection) {
foreach (var col in child.ContentProperty.CollectionElements) {
if (col.ContentProperty != null && col.ContentProperty.IsCollection) {
if (CollectionSupport.CanCollectionAdd(col.ContentProperty.ReturnType, pastedItems.Select(item => item.Component))) {
pasted = true;
}
}
}
break;
} else if (child.ContentProperty.Value != null) {
child = child.ContentProperty.Value;
} else if (pastedItems.Count == 1) {
child.ContentProperty.SetValue(pastedItems.First().Component);
pasted = true;
break;
} else
break;
} else
break;
}
changeGroup.Commit();
}
}
示例10: TestPackageInstallFailure
// Test for package install failure
private static void TestPackageInstallFailure()
{
var failedPackages = new Collection<ToolPackage> { PACKAGE_1, PACKAGE_4 };
var stringWriter = new StringWriter();
const string errorText = "This is the Tool Error Text!"; // Not L10N
var rInstaller = FormatPackageInstaller(stringToWrite: errorText, missingPackages: failedPackages,
writer: stringWriter);
var messageDlg = ShowDialog<MessageDlg>(rInstaller.OkDialog);
List<string> failedPackagesTitles = failedPackages.Select(f => f.Name).ToList();
RunUI(() => Assert.AreEqual(TextUtil.LineSeparate(Resources.RInstaller_InstallPackages_The_following_packages_failed_to_install_,
string.Empty,
TextUtil.LineSeparate(failedPackagesTitles),
string.Empty,
Resources.RInstaller_InstallPackages_Output_logged_to_the_Immediate_Window_),
messageDlg.Message));
string outText = stringWriter.ToString();
Assert.IsTrue(outText.Contains(errorText));
OkDialog(messageDlg, messageDlg.OkDialog);
WaitForClosedForm(rInstaller);
}
示例11: Validate
public IEnumerable<IValidationResult> Validate(object instance, bool stopOnFirstError = false)
{
var results = new Collection<ValidationResult>();
Validate(new ValidationContext(instance, provider, null), results, validateAllProperties: !stopOnFirstError);
return results.Select(result => new ResultAdapter(result));
}
示例12: DataListUtil_UpsertTokens_ValidTokenizer_AddsSuffixToKey
public void DataListUtil_UpsertTokens_ValidTokenizer_AddsSuffixToKey()
{
//------------Setup for test--------------------------
const int TokenCount = 5;
var tokenNumber = 0;
var tokenizer = new Mock<IDev2Tokenizer>();
tokenizer.Setup(t => t.HasMoreOps()).Returns(() => tokenNumber < TokenCount);
tokenizer.Setup(t => t.NextToken()).Returns(() => string.Format("[[Var{0}]]", tokenNumber++));
var target = new Collection<ObservablePair<string, string>>();
//------------Execute Test---------------------------
DataListUtil.UpsertTokens(target, tokenizer.Object, "prefix", "suffix");
//------------Assert Results-------------------------
Assert.AreEqual(TokenCount, target.Count);
var keys = target.Select(p => p.Key);
var i = 0;
foreach(var key in keys)
{
var expected = string.Format("[[prefixVar{0}suffix]]", i++);
Assert.AreEqual(expected, key);
}
}
示例13: AssertMultipleFoldersOutputAtLeast
private static void AssertMultipleFoldersOutputAtLeast(int atLeast, Collection<PSObject> output)
{
Assert.IsNotNull(output);
Assert.IsTrue(atLeast <= output.Count);
CollectionAssert.AllItemsAreNotNull(output);
CollectionAssert.AllItemsAreUnique(output);
CollectionAssert.AllItemsAreInstancesOfType(output.Select(pso => pso.BaseObject).ToArray(), typeof(KnownFolder));
var outputIds = output.Select(pso => pso.BaseObject).Cast<KnownFolder>().Select(kf => kf.FolderId).ToArray();
CollectionAssert.AllItemsAreUnique(outputIds);
}
示例14: AssertMultipleFoldersOutput
private static void AssertMultipleFoldersOutput(ICollection<Guid> expected, Collection<PSObject> output)
{
Assert.IsNotNull(output);
////Assert.AreEqual(expected.Count, output.Count);
CollectionAssert.AllItemsAreNotNull(output);
CollectionAssert.AllItemsAreUnique(output);
CollectionAssert.AllItemsAreInstancesOfType(output.Select(pso => pso.BaseObject).ToArray(), typeof(KnownFolder));
var outputIds = output.Select(pso => pso.BaseObject).Cast<KnownFolder>().Select(kf => kf.FolderId).ToArray();
CollectionAssert.AllItemsAreUnique(outputIds);
CollectionAssert.AreEquivalent(expected.ToArray(), outputIds);
}
示例15: DataListUtil_UpsertTokens_ValidTokenizer_ClearsTargetFirst
public void DataListUtil_UpsertTokens_ValidTokenizer_ClearsTargetFirst()
{
//------------Setup for test--------------------------
const int TokenCount1 = 5;
var tokenNumber1 = 0;
var tokenizer = new Mock<IDev2Tokenizer>();
tokenizer.Setup(t => t.HasMoreOps()).Returns(() => tokenNumber1 < TokenCount1);
tokenizer.Setup(t => t.NextToken()).Returns(() => string.Format("[[Var{0}]]", tokenNumber1++));
var target = new Collection<ObservablePair<string, string>>();
DataListUtil.UpsertTokens(target, tokenizer.Object);
// Create a second tokenizer that will return 2 vars with the same name as the first tokenizer and 1 new one
const int ExpectedCount = 3;
const int TokenCount2 = 6;
var tokenNumber2 = 3;
var tokenizer2 = new Mock<IDev2Tokenizer>();
tokenizer2.Setup(t => t.HasMoreOps()).Returns(() => tokenNumber2 < TokenCount2);
tokenizer2.Setup(t => t.NextToken()).Returns(() => string.Format("[[Var{0}]]", tokenNumber2++));
//------------Execute Test---------------------------
DataListUtil.UpsertTokens(target, tokenizer2.Object);
//------------Assert Results-------------------------
Assert.AreEqual(ExpectedCount, target.Count);
// Expect only vars from second tokenizer
var keys = target.Select(p => p.Key);
var i = 3;
foreach(var key in keys)
{
var expected = string.Format("[[Var{0}]]", i++);
Assert.AreEqual(expected, key);
}
}