本文整理汇总了C#中List.SelectMany方法的典型用法代码示例。如果您正苦于以下问题:C# List.SelectMany方法的具体用法?C# List.SelectMany怎么用?C# List.SelectMany使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类List
的用法示例。
在下文中一共展示了List.SelectMany方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: FindServiceProvider
internal static IServiceProvider FindServiceProvider(Assembly[] assembliesToSearch = null) {
var assemblies = new List<Assembly>();
if (assembliesToSearch != null && assembliesToSearch.Length > 0) {
assemblies.AddRange(assembliesToSearch);
} else {
try {
var entryAssembly = Assembly.GetEntryAssembly();
if (entryAssembly != null)
assemblies.Add(entryAssembly);
} catch {}
}
var serviceProviderTypes = assemblies.SelectMany(a =>
a.GetTypes().Where(t => !t.IsInterface && !t.IsAbstract && typeof(IBootstrappedServiceProvider).IsAssignableFrom(t)));
foreach (var serviceProviderType in serviceProviderTypes) {
var bootstrapper = Activator.CreateInstance(serviceProviderType) as IServiceProvider;
if (bootstrapper != null)
return bootstrapper;
}
serviceProviderTypes = assemblies.SelectMany(a => a.GetTypes()
.Where(t => !t.IsInterface && !t.IsAbstract && typeof(IServiceProvider).IsAssignableFrom(t)));
foreach (var serviceProviderType in serviceProviderTypes) {
var bootstrapper = Activator.CreateInstance(serviceProviderType) as IServiceProvider;
if (bootstrapper != null)
return bootstrapper;
}
return new ActivatorServiceProvider();
}
示例2: FindAndGetServiceProvider
public static IServiceProvider FindAndGetServiceProvider(ILoggerFactory loggerFactory, params Assembly[] assembliesToSearch) {
var assemblies = new List<Assembly>();
if (assembliesToSearch != null && assembliesToSearch.Length > 0) {
assemblies.AddRange(assembliesToSearch);
} else {
try {
var entryAssembly = Assembly.GetEntryAssembly();
if (entryAssembly != null)
assemblies.Add(entryAssembly);
} catch { }
}
// try to find bootstrapped service providers first
var serviceProviderTypes = assemblies.SelectMany(a =>
a.GetTypes().Where(t => !t.GetTypeInfo().IsInterface && !t.GetTypeInfo().IsAbstract && typeof(IBootstrappedServiceProvider).IsAssignableFrom(t)));
foreach (var serviceProviderType in serviceProviderTypes) {
var serviceProvider = GetServiceProvider(serviceProviderType, loggerFactory);
if (serviceProvider != null)
return serviceProvider;
}
// find any service providers
serviceProviderTypes = assemblies.SelectMany(a => a.GetTypes()
.Where(t => !t.GetTypeInfo().IsInterface && !t.GetTypeInfo().IsAbstract && typeof(IServiceProvider).IsAssignableFrom(t)));
foreach (var serviceProviderType in serviceProviderTypes) {
var serviceProvider = GetServiceProvider(serviceProviderType, loggerFactory);
if (serviceProvider != null)
return serviceProvider;
}
return new ActivatorServiceProvider();
}
示例3: ShowExample
public static void ShowExample()
{
#region DATA
PERSON p1 = new PERSON() { Name = "Martin Hromek" };
p1.PhoneNumbers = new List<PHONENUMBER>();
p1.PhoneNumbers.Add(new PHONENUMBER() { Number = "+420775656055" });
PERSON p2 = new PERSON() { Name = "Eva Brezovska" };
p2.PhoneNumbers = new List<PHONENUMBER>();
p2.PhoneNumbers.Add(new PHONENUMBER() { Number = "+420723195654" });
List<PERSON> list = new List<PERSON>();
list.Add(p1);
list.Add(p2);
#endregion
// SELECT
IEnumerable<IEnumerable<PHONENUMBER>> phoneList = list.Select(p => p.PhoneNumbers);
// SELECT MANY
Console.WriteLine("\nSelectMany:");
Console.WriteLine("Vstupni pole: phone list");
Console.WriteLine("Spojim [SelectMany] seznam telefonich cisle.");
IEnumerable<PHONENUMBER> phonesList = list.SelectMany(p => p.PhoneNumbers);
Console.WriteLine("SelectMany: {0}", string.Join(",", phonesList));
// SELECT MANY WITH ANONYMOUS CLASS
var dictionary = list.SelectMany(p => p.PhoneNumbers, (parent, child) => new { name = parent.Name, parent.PhoneNumbers });
}
示例4: Sync
public SyncResponse Sync(string serverKey, List<PluginResource> discoveries = null, List<AnalyzerResult> metricResults = null, Dictionary<string, string> commandResults = null)
{
if (AgentContext.Current.PluginBlacklist != null)
{
discoveries = discoveries.Where(p => !AgentContext.Current.PluginBlacklist.Contains(p.Category, StringComparer.InvariantCultureIgnoreCase)).ToList();
}
// build payload
var payLoad = new SyncRequest();
payLoad.AddPluginResources(discoveries);
payLoad.AddCommandResults(commandResults);
if (metricResults != null && metricResults.Any())
{
payLoad.AddCollectedMetrics(metricResults.SelectMany(r => r.Metrics).ToList());
payLoad.AddAnomalies(metricResults.SelectMany(r => r.Anomalies).ToList());
}
payLoad.AddRegisteredCustomMetrics();
payLoad.AddUpdateConfig();
payLoad.AddAgentVersion();
Log.DebugFormat("Syncing payload with cloud service:\n{0}", JsonConvert.SerializeObject(payLoad, Formatting.Indented));
// send request
var response = RestHelper.Post<JObject>("sync", new AggregatorAuthenticator(serverKey), r => r.AddBody(payLoad), r =>
{
Log.ErrorFormat("Call to /sync resulted in an error with status code {0} ({1})", r.StatusCode, r.StatusDescription);
});
// parse response
if (response != null)
{
Log.DebugFormat("Received sync response from cloud:\n{0}", response.ToString(Formatting.Indented));
var syncResponse = new SyncResponse();
if (response["schedules"] != null)
{
var newSchedules = ParsePluginResourceSchedulesFromJson(response["schedules"]);
if (newSchedules.Any())
{
syncResponse.PluginResourcesSchedules = newSchedules;
}
}
var newCommands = response["commands"];
if (newCommands != null && newCommands.Any())
{
syncResponse.AdminCommands = ((IDictionary<string, JToken>)newCommands).ToDictionary(c => c.Key, c => c.Value.Value<string>());
}
return syncResponse;
}
return null;
}
示例5: Filter
public static DependencyGraph Filter(DependencyGraph graph, List<OutputEntry> warnings)
{
var projs = new HashSet<Library>(warnings.SelectMany(w => w.Projects)
.Concat(warnings.SelectMany(w => w.Dependencies.SelectMany(d => new[] { d.Source, d.Target }))));
var deps = new HashSet<Dependency>(warnings.SelectMany(w => w.Dependencies));
var filtered = new DependencyGraph();
filtered.AddVertexRange(projs);
//filtered.AddEdgeRange(graph.Edges.Where(d => projs.Contains(d.Source) && projs.Contains(d.Target)));
filtered.AddEdgeRange(deps);
return filtered;
}
示例6: Run
public void Run(List<SampleTri> mesh)
{
Parallel.ForEach(mesh.SelectMany(m => m.Samples).Distinct().ToList(), sample =>
{
var neighbours = sample.DepthNeighbours(Depth);
var colors = neighbours.Select(s => s.Color).OrderByDescending(c => c.Saturation).ToList();
sample.NewColor = colors.Last();
});
Parallel.ForEach(mesh.SelectMany(m => m.Samples).Distinct().ToList(), sample =>
{
sample.Color = sample.NewColor;
});
}
示例7: GetFileForNamespaceGroup
private FileToWrite GetFileForNamespaceGroup(string @namespace, List<ToTypeScript> toTypeScripts)
{
bool containsControllers = toTypeScripts.Any(obj => obj.ObjectType == ObjectType.Controller);
// add static import only if the files is going to contains controllers
var extraImport = containsControllers ? new[] { $"import {{ RestApi, RequestConfig }} from '../Nimrod';" } : new string[0];
var imports = toTypeScripts
.SelectMany(t => t.GetImports())
// do not write import for the same namespace
.Where(import => import.Namespace != @namespace)
.GroupBy(import => import.Namespace)
.Select(grp => $"import * as {grp.Key.Replace('.', '_')} from './{ grp.Key}';")
.OrderBy(importLine => importLine);
var content = toTypeScripts.SelectMany(t => t.GetLines());
return new FileToWrite($"{@namespace}", extraImport.Concat(imports).Concat(content));
}
示例8: Main
static void Main(string[] args)
{
// parse args
string cwd = Environment.CurrentDirectory;
var testdirs = new List<string>();
string phpexepath = Path.Combine(cwd, "php.exe");
foreach (var arg in args)
{
if (arg.EndsWith("php.exe", StringComparison.OrdinalIgnoreCase))
{
phpexepath = arg;
}
else
{
testdirs.Add(Path.GetFullPath(Path.Combine(cwd, arg)));
}
}
// run tests lazily
var tests = testdirs
.SelectMany(dir => ExpandTestDir(dir));
// output results
foreach (var test in tests)
{
Console.Write($"{test} ... ");
Console.WriteLine(TestCore(test, phpexepath));
}
}
示例9: feed_Loaded
private static void feed_Loaded(object sender, SyndicationResourceLoadedEventArgs e)
{
var feed = (RssFeed)sender;
feed.Loaded -= feed_Loaded;
Console.WriteLine("RSS Feed loaded at " + DateTime.UtcNow);
List<string[]> allLines = new List<string[]>();
foreach (var rssItem in feed.Channel.Items)
{
string title = rssItem.Title;
title = RemoveHtml(title);
if (m_includeDescription)
{
string description = rssItem.Description;
description = RemoveHtml(description);
allLines.Add(new string[] { title + ": " + description });
}
else
{
allLines.Add(new string[] { title });
}
}
lock (m_forecastFeedLines)
{
m_forecastFeedLines.Clear();
m_forecastFeedLines.AddRange(allLines.SelectMany(s => s));
}
UpdateAllFeedLines();
}
示例10: Run
public override Population Run()
{
var m = GetOption("select_count", Math.Ceiling((double) (Population.Osobi.Count/20)));
if (Population.Osobi.Count < m) return Population;
var groups =new List < List<Unit> >();
var tempc = 0;
var templ = new List<Unit>();
for (int i = 0; i < Population.Osobi.Count; i++)
{
var unit = Population.Osobi[i];
if (tempc>=m)
{
groups.Add(templ);
templ=new List<Unit>();
tempc = 0;
}
templ.Add(unit);
tempc++;
}
if (templ.Count > 0) { groups.Add(templ);templ=new List<Unit>();}
var goods=groups.SelectMany(u => u.Where(u1 => u1.Function == u.Max(u2 => u2.Function)));
Population.TempPopulation = goods.Select(u=>u.Id).ToList();
return Population;
}
示例11: GetApplications
/// <summary>
/// Gets the metro applications.
/// </summary>
/// <returns></returns>
public static IEnumerable<MetroApplication> GetApplications()
{
var packages = new PackageManager()
.FindPackagesForUser(WindowsIdentity.GetCurrent().User.Value);
var metroPackages = new List<MetroPackage>();
foreach (var package in packages)
{
var metroPackage = new MetroPackage(package);
if (metroPackage.Applications.Any())
{
metroPackages.Add(new MetroPackage(package));
}
}
var metroApplications = metroPackages
.SelectMany(package => package.Applications)
.Where(
application =>
!string.IsNullOrEmpty(application.AppUserModelId) &&
!string.IsNullOrEmpty(application.Name));
return metroApplications;
}
示例12: ScanIndex
public ScanIndex()
{
AssemblyTypes = new Dictionary<Assembly, List<Type>>();
TypeAssemblies = new Dictionary<Type, Assembly>();
ImplementorsOfType = new Dictionary<Type, List<Type>>();
TypeHierarchies = new Dictionary<Type, List<Type>>();
Closers = new Dictionary<Type, List<Type>>();
AssemblyExclusionList = new List<string>();
ReferenceLookup = new Dictionary<Assembly, List<Assembly>>();
ConfiguredSymbiotes = new Dictionary<Assembly, bool>();
SingleImplementations = new Dictionary<Type, Type>();
Scanner = new TypeScanner();
InitExclusions();
var initialList = new List<Assembly>( Scanner.GetAssembliesFromBaseDirectory().ToList() );
var references = initialList
.SelectMany( GetReferenceList )
.ToList();
initialList.AddRange( references.Where( r => !initialList.Any( a => a.FullName.Equals( r.FullName ) ) ) );
var uniqueList = initialList.Distinct();
var filtered = uniqueList.Where( x => !AssemblyExclusionList.Any( e => x.FullName.StartsWith( e ) ) );
CompleteAssemblyList = new List<Assembly>( filtered.ToList() );
}
示例13: Eject
public IEnumerable<Money> Eject(CashDeal inCash, ChangePool inReservedMoney)
{
try {
if (inCash.UsedAmount == 0) {
return inCash.RecevedMoney.ToList();
}
var result = new List<KeyValuePair<Money, int>>();
this.EjectCore(
inCash.ChangedAount,
inReservedMoney.Items.OrderByDescending(pair => pair.Key.Value()),
(m, totalCount, useCount) => {
result.Add(
new KeyValuePair<Money, int>(m, (int)useCount)
);
}
);
return result.SelectMany(r => Enumerable.Repeat(r.Key, r.Value));
}
finally {
inCash.RecevedMoney.Clear();
}
}
示例14: Subscribe
public Task Subscribe(Guid recordID, string group)
{
if (UserList.Any(x => x.User == Context.ConnectionId))
return null;
Console.WriteLine("[{0}] Client '{1}' has been added to group {2}.", DateTime.Now.ToString("dd-mm-yyyy hh:MM:ss"), Context.ConnectionId, group);
var adv = new AdvList
{
Name = @group,
User = Context.ConnectionId,
UserRecordID = recordID,
ListOfLanes = new List<Guid>()
};
List<CustomerHierarchy> chList = new List<CustomerHierarchy>();
if(!CustomerHierarchy.Load(recordID, out chList))
{
Console.WriteLine("Error retrieving customer hierarchy for user " + User.LoadUser(recordID).DisplayName);
}
var listOfLanes = new List<Guid>();
adv.ListOfLanes = chList.SelectMany(x => x.Equipment.Select(e => e.RecordID)).Distinct().ToList();
UserList.Add(adv);
Console.WriteLine("user list contains this many people on subscription" + UserList.Count());
return Groups.Add(Context.ConnectionId, group);
}
示例15: Write
public void Write(List<PackageViewModel> packages, string file)
{
if (string.IsNullOrWhiteSpace(file))
{
file = "packages.dgml";
}
XNamespace ns = "http://schemas.microsoft.com/vs/2009/dgml";
var colors = new DgmlColorConfiguration();
var nodes =
packages
.Select(
package =>
new XElement(ns + "Node",
new XAttribute("Id", package.Id),
new XAttribute("Label", string.Format("{0} ({1})", package.NugetId, package.LocalVersion)),
new XAttribute("Background", GraphHelper.GenerateBackgroundColor(packages, package, colors))))
.ToList();
var links =
(packages
.SelectMany(
package => package.Dependencies, (package, dep) =>
new XElement(ns + "Link",
new XAttribute("Source", package.Id),
new XAttribute("Target", packages.Any(x => x.NugetId == dep.NugetId && x.LocalVersion == dep.Version) ? packages.First(x => x.NugetId == dep.NugetId && x.LocalVersion == dep.Version).Id : string.Format("{0} ({1})", dep.NugetId, dep.Version)))))
.ToList();
var document =
new XDocument(
new XDeclaration("1.0", "utf-8", string.Empty),
new XElement(ns + "DirectedGraph", new XElement(ns + "Nodes", nodes), new XElement(ns + "Links", links)));
document.Save(file);
}