本文整理汇总了C#中IDictionary.SelectMany方法的典型用法代码示例。如果您正苦于以下问题:C# IDictionary.SelectMany方法的具体用法?C# IDictionary.SelectMany怎么用?C# IDictionary.SelectMany使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IDictionary
的用法示例。
在下文中一共展示了IDictionary.SelectMany方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ConstructErrorString
public static string ConstructErrorString(IDictionary<string, IList<ModelValidationError>> errors)
{
List<string> errorList = new List<string>();
foreach (var x in errors.SelectMany(p => p.Value.Select(e => new { Property = p.Key, Properties = e.MemberNames.ToList(), Error = e.ErrorMessage })))
{
errorList.Add(string.Format("Error with property {0}: {1}", x.Property, x.Error));
}
string errorString = string.Join("\n\n", errorList);
return errorString;
}
示例2: CanMigrate
public bool CanMigrate(IDictionary<string, List<MigrationStep>> steps)
{
foreach (MigrationStep step in steps.SelectMany(row => row.Value).OrderBy(row => row.Version))
{
MigrationReference migrationReference = step.MigrationReference;
IMigrationFactory migrationFactory = _migrationFactoryChooser.ChooseFactory(migrationReference);
IDatabaseMigration migration = migrationFactory.CreateMigration(migrationReference);
step.DatabaseMigration = migration;
_migrationInitializer.InitializeMigration(migration);
}
_log.Info("All migrations are initialized.");
return true;
}
示例3: WriteStats
private static void WriteStats(StreamWriter sw, IDictionary<File, string> files, TypeDefinition[] types, int total)
{
var stats = files.SelectMany(x => x.Key.Annotations).Select(x => x.Type)
.GroupBy(x => x)
.Select(x => new {Type = types.First(y => y.Name == x.Key).Display, Count = x.Count()})
.OrderBy(x => x.Type)
.ToArray();
foreach (var stat in stats)
{
sw.WriteLine("<tr><th>{0}:</th><td>{1}</td></tr>", WebUtility.HtmlEncode(stat.Type), stat.Count);
}
if (stats.Length != 1)
{
sw.WriteLine("<tr><th>Total:</th><td>{0}</td></tr>", total);
}
}
示例4: Genie
// ReSharper restore UnusedMember.Local
public Genie(IDictionary<string, AnswerStatistic> answerStatistics, int answeringChoicesCount)
{
this.answerStatistics = answerStatistics;
this.answeringChoicesCount = answeringChoicesCount;
answersGuessedCount = answerStatistics.Sum(s => s.Value.AnswerCount);
questionStatistics = answerStatistics.SelectMany(s => s.Value.AnsweredQuestionsById)
.GroupBy(p => p.Key)
.ToDictionary(g => g.Key, g => new QuestionStatistic
{
ChoicesFrequencies = g.Aggregate(new int[answeringChoicesCount], (curr, p) =>
{
for (int i = 0; i < answeringChoicesCount; i++)
{
curr[i] += p.Value.ChoicesFrequencies[i];
}
return curr;
})
});
}
示例5: Migrate
public void Migrate(IDictionary<string, List<MigrationStep>> steps)
{
foreach (MigrationStep step in steps.SelectMany(row => row.Value).OrderBy(row => row.Version))
{
_log.Info(step);
using (Machine.Core.LoggingUtilities.Log4NetNdc.Push("{0}", step.MigrationReference.Name))
{
_configuration.ActiveConfigurationKey = step.MigrationReference.ConfigurationKey;
if (!_configuration.ShowDiagnostics)
{
IDbTransaction transaction = null;
try
{
transaction = _transactionProvider.Begin();
step.Apply();
if (step.Reverting)
{
_schemaStateManager.SetMigrationVersionUnapplied(step.Version, _configuration.Scope);
}
else
{
_schemaStateManager.SetMigrationVersionApplied(step.Version, _configuration.Scope);
}
_log.InfoFormat("Comitting");
transaction.Commit();
}
catch (Exception)
{
if (transaction != null)
{
_log.InfoFormat("Rollback");
transaction.Rollback();
}
throw;
}
finally
{
_configuration.ActiveConfigurationKey = null;
}
}
}
}
}
示例6: SendRequest
public static RequestDetails SendRequest(this WebHost webHost, string urlPath, IDictionary<string, IEnumerable<string>> postData) {
var physicalPath = Bleroy.FluentPath.Path.Get(webHost.PhysicalDirectory);
var details = new RequestDetails {
HostName = webHost.HostName,
UrlPath = urlPath,
Page = physicalPath
.Combine(urlPath.TrimStart('/', '\\'))
.GetRelativePath(physicalPath),
};
if (!string.IsNullOrEmpty(webHost.Cookies)) {
details.RequestHeaders.Add("Cookie", webHost.Cookies);
}
if (postData != null) {
var requestBodyText = postData
.SelectMany(kv => kv.Value.Select(v => new { k = kv.Key, v }))
.Select((kv, n) => new { p = HttpUtility.UrlEncode(kv.k) + "=" + HttpUtility.UrlEncode(kv.v), n })
.Aggregate("", (a, x) => a + (x.n == 0 ? "" : "&") + x.p);
details.PostData = Encoding.Default.GetBytes(requestBodyText);
}
webHost.Execute(() => {
var output = new StringWriter();
var worker = new Worker(details, output);
HttpRuntime.ProcessRequest(worker);
details.ResponseText = output.ToString();
});
string setCookie;
if (details.ResponseHeaders.TryGetValue("Set-Cookie", out setCookie)) {
Trace.WriteLine(string.Format("Set-Cookie: {0}", setCookie));
webHost.Cookies = (webHost.Cookies + ';' + setCookie.Split(';').FirstOrDefault()).Trim(';');
}
return details;
}
示例7: SendRequest
public static RequestDetails SendRequest(this WebHost webHost, string urlPath, IDictionary<string, IEnumerable<string>> postData, string requestMethod = null) {
var physicalPath = Bleroy.FluentPath.Path.Get(webHost.PhysicalDirectory);
bool isHomepage = urlPath == "/";
if (!isHomepage)
urlPath = StripVDir(urlPath, webHost.VirtualDirectory);
var details = new RequestDetails {
HostName = webHost.HostName,
UrlPath = urlPath.Replace('\\', '/'),
};
int queryIndex = urlPath.IndexOf('?');
if (queryIndex >= 0) {
details.UrlPath = urlPath.Substring(0, queryIndex).Replace('\\', '/');
details.Query = urlPath.Substring(queryIndex + 1);
}
var physicalFilePath = physicalPath.Combine(details.UrlPath.TrimStart('/', '\\'));
details.Page = (isHomepage ? "" : physicalFilePath.GetRelativePath(physicalPath).ToString());
if (!File.Exists(physicalFilePath))
details.Page = details.Page.Replace('\\', '/');
if (!string.IsNullOrEmpty(webHost.Cookies)) {
details.RequestHeaders.Add("Cookie", webHost.Cookies);
}
if (postData != null) {
var requestBodyText = postData
.SelectMany(kv => kv.Value.Select(v => new { k = kv.Key, v }))
.Select((kv, n) => new { p = HttpUtility.UrlEncode(kv.k) + "=" + HttpUtility.UrlEncode(kv.v), n })
.Aggregate("", (a, x) => a + (x.n == 0 ? "" : "&") + x.p);
if (requestMethod == "POST")
details.PostData = Encoding.Default.GetBytes(requestBodyText);
else
details.Query = requestBodyText;
}
webHost.Execute(() => {
var output = new StringWriter();
var worker = new Worker(details, output);
HttpRuntime.ProcessRequest(worker);
details.ResponseText = output.ToString();
});
string setCookie;
if (details.ResponseHeaders.TryGetValue("Set-Cookie", out setCookie)) {
Trace.WriteLine(string.Format("Set-Cookie: {0}", setCookie));
var cookieName = setCookie.Split(';')[0].Split('=')[0];
DateTime expires;
if (!string.IsNullOrEmpty(webHost.Cookies)
&& setCookie.Contains("expires=")
&& DateTime.TryParse(setCookie.Split(new[] { "expires=" }, 2, StringSplitOptions.None)[1].Split(';')[0], out expires)
&& expires < DateTime.Now) {
// remove
Trace.WriteLine(string.Format("Removing cookie: {0}", cookieName));
webHost.Cookies = Regex.Replace(webHost.Cookies, string.Format("{0}=[^;]*;?", cookieName), "");
}
else if (!string.IsNullOrEmpty(webHost.Cookies)
&& Regex.IsMatch(webHost.Cookies, string.Format("\b{0}=", cookieName))) {
// replace
Trace.WriteLine(string.Format("Replacing cookie: {0}", cookieName));
webHost.Cookies = Regex.Replace(webHost.Cookies, string.Format("{0}=[^;]*(;?)", cookieName), string.Format("{0}$1", setCookie.Split(';')[0]));
}
else {
// add
Trace.WriteLine(string.Format("Adding cookie: {0}", cookieName));
webHost.Cookies = (webHost.Cookies + ';' + setCookie.Split(';').FirstOrDefault()).Trim(';');
}
Trace.WriteLine(string.Format("Cookie jar: {0}", webHost.Cookies));
}
return details;
}
示例8: GetCategories
private IEnumerable<TranslationCategory> GetCategories(IDictionary<string, TranslationFile> translation)
{
return translation.SelectMany(pair => pair.Value.TranslationCategories);
}
示例9: CleanCache
private void CleanCache(IDictionary<char, List<Mesh>> cache, bool empty)
{
if (empty)
{
//Discard everything in this cache
foreach (var mesh in cache.SelectMany(item => item.Value))
{
//We're sharing buffers, so disposing them now would be very bad! Set them to null to make sure they're not disposed
mesh.IndexBuffer = null;
mesh.VertexBuffer = null;
//Dispose the mesh
mesh.Dispose();
}
cache.Clear();
}
else
{
//Find all keys with an empty cache
foreach (var item in cache)
if (item.Value.Count == 0)
_cleanup.Add(item.Key);
//Remove all the useless keys
foreach (var character in _cleanup)
cache.Remove(character);
_cleanup.Clear();
}
}
示例10: ResultEvaluation
public string ResultEvaluation(IDictionary<ClassType, List<CustomImage<ClassType>>> imgDictionary)
{
var result = new StringBuilder();
var total = 0;
foreach (var key in imgDictionary.Keys)
{
int guessedImages = 0;
foreach (var customImage in imgDictionary[key])
{
guessedImages += DefineImage(customImage) == key ? 1 : 0;
}
total += guessedImages;
result.Append(string.Format("\n{0}: {1}", key,
((double)guessedImages * 100 / imgDictionary[key].Count).ToString("F")));
}
result.Append(string.Format("\nВсего: {0}",
((double)total * 100 / imgDictionary.SelectMany(x => x.Value).Count()).ToString("F")));
return result.ToString();
}
示例11: SerializeSafe
public static bool SerializeSafe(this IZipper _Zipper, IDictionary<string, string> idic, string iFilename, string ipassword)
{
return _Zipper.Zipp(idic.SelectMany(kvp => new string[] { kvp.Key, kvp.Value }), iFilename, ipassword);
}
示例12: renderCollidingFaces
public void renderCollidingFaces(ModelGeometry collisionGeometry, IDictionary<Face, uint> collidingFaces, Camera camera, uint min, uint max)
{
if (collidingFaces.Count > 0)
{
// fill vertex buffer with collision geometry and set on device
{
float range = Math.Max(max - min, 0.0001f);
var data = collidingFaces.SelectMany(face =>
{
var colour = new Vector3((face.Value - min)/range);
return new[]
{
collisionGeometry.vertices[face.Key.v1],
collisionGeometry.normals[face.Key.n1],
colour,
collisionGeometry.vertices[face.Key.v2],
collisionGeometry.normals[face.Key.n2],
colour,
collisionGeometry.vertices[face.Key.v3],
collisionGeometry.normals[face.Key.n3],
colour
};
});
mCollidingFacesVertices.SetData<Vector3>(data.ToArray());
mGraphicsDevice.SetVertexBuffer(mCollidingFacesVertices);
}
// enable alpha blending
var previousBlendState = mGraphicsDevice.BlendState;
mGraphicsDevice.BlendState = mAlphaBlendState;
// draw
mCollisionsShader.Parameters["WorldViewProjection"].SetValue(camera.viewMatrix * camera.projectionMatrix);
mCollisionsShader.CurrentTechnique.Passes[0].Apply();
mGraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, collidingFaces.Count);
// restore previous blend mode
mGraphicsDevice.BlendState = previousBlendState;
}
}
示例13: AddAssignment
/// <summary>
/// Creates a new assignment with the given data.
/// </summary>
public TestDatabaseBuilder AddAssignment(
string classroomName,
string assignmentGroupName,
string assignmentName,
IDictionary<string, DateTime> sectionDueDates,
IDictionary<string, string[]> questionsByCategory)
{
var classroom = _buildContext.Classrooms
.Include(c => c.Sections)
.Single(c => c.Name == classroomName);
var sections = classroom.Sections
.ToDictionary(s => s.Name, s => s.Id);
var allQuestions = _buildContext.Questions
.Include(q => q.QuestionCategory)
.ToList()
.GroupBy(q => q.QuestionCategory.Name)
.ToDictionary(group => group.Key, group => group.ToDictionary(q => q.Name, q => q.Id));
var assignment = new Assignment()
{
ClassroomId = classroom.Id,
Name = assignmentName,
GroupName = assignmentGroupName,
DueDates = sectionDueDates.Select
(
kvp => new AssignmentDueDate()
{
SectionId = sections[kvp.Key],
DueDate = kvp.Value
}
).ToList(),
Questions = questionsByCategory.SelectMany
(
qs => qs.Value,
(kvp, questionName) => new AssignmentQuestion()
{
QuestionId = allQuestions[kvp.Key][questionName],
Points = 1.0
}
).ToList()
};
_buildContext.Assignments.Add(assignment);
_buildContext.SaveChanges();
return this;
}
示例14: ResolveOperations
public IList<PackageOperation> ResolveOperations(IEnumerable<IPackage> packages, out IList<IPackage> packagesByDependencyOrder, bool allowPrereleaseVersionsBasedOnPackage = false)
{
_packagesByDependencyOrder = new Dictionary<string, IList<IPackage>>();
_operations.Clear();
Marker.Clear();
_packagesToKeep.Clear();
Debug.Assert(Operations is List<PackageOperation>);
foreach (var package in packages)
{
if (!_operations.Contains(package, PackageAction.Install))
{
var allowPrereleaseVersions = _allowPrereleaseVersions;
try
{
if (allowPrereleaseVersionsBasedOnPackage)
{
// Update _allowPrereleaseVersions before walking a package if allowPrereleaseVersionsBasedOnPackage is set to true
// This is mainly used when bulk resolving operations for reinstalling packages
_allowPrereleaseVersions = _allowPrereleaseVersions || !package.IsReleaseVersion();
}
Walk(package);
}
finally
{
_allowPrereleaseVersions = allowPrereleaseVersions;
}
}
}
// Flatten the dictionary to create a list of all the packages. Only this item the packages visited first during the walk will appear on the list. Also, only retain distinct elements
IEnumerable<IPackage> allPackagesByDependencyOrder = _packagesByDependencyOrder.SelectMany(p => p.Value).Distinct();
// Only retain the packages for which the operations are being resolved for
packagesByDependencyOrder = allPackagesByDependencyOrder.Where(p => packages.Any(q => p.Id == q.Id && p.Version == q.Version)).ToList();
Debug.Assert(packagesByDependencyOrder.Count == packages.Count());
_packagesByDependencyOrder.Clear();
_packagesByDependencyOrder = null;
return Operations.Reduce();
}
示例15: Transform
public static IDictionary<string, int> Transform(IDictionary<int, IList<string>> input)
{
return input.SelectMany(kvp => kvp.Value.Select(c => new KeyValuePair<string, int>(c.ToLower(), kvp.Key)))
.ToDictionary(p => p.Key, p => p.Value);
}