首页 \ 问答 \ 如何为每个hashmap?(How to for each the hashmap? [duplicate])

如何为每个hashmap?(How to for each the hashmap? [duplicate])

这个问题已经在这里有一个答案:

  • 如何有效地迭代地图中的每个条目? 33答案

我有这个字段:

HashMap<String, HashMap> selects = new HashMap<String, HashMap>();

对于每个Hash<String, HashMap>我需要创建一个ComboBox ,它的项目是HashMap <String, **HashMap**>的值(恰好是HashMap本身)。

通过(不起作用)演示:

for (int i=0; i < selects.size(); i++) {
    HashMap h = selects[i].getValue();
    ComboBox cb = new ComboBox();

    for (int y=0; y < h.size(); i++) {
        cb.items.add(h[y].getValue);
    }
}

This question already has an answer here:

I have this field:

HashMap<String, HashMap> selects = new HashMap<String, HashMap>();

For each Hash<String, HashMap> I need to create a ComboBox, whose items are the value (which happens to be a HashMap itself) of HashMap <String, **HashMap**>.

By way of (non-functioning) demonstration:

for (int i=0; i < selects.size(); i++) {
    HashMap h = selects[i].getValue();
    ComboBox cb = new ComboBox();

    for (int y=0; y < h.size(); i++) {
        cb.items.add(h[y].getValue);
    }
}

原文:https://stackoverflow.com/questions/4234985
更新时间:2022-03-28 07:03

最满意答案

这取决于您的存储库类的设置方式。 如果您正在立即执行查询,即如果您的GetAll()方法返回类似IEnumerable<T>IList<T> ,那么是的,这可能很容易成为性能问题,您通常应该避免这种情况,除非你真的想一次加载所有记录。

另一方面,如果您的GetAll()方法返回IQueryable<T> ,则可能根本没有问题,具体取决于您是否信任编写查询的人。 返回IQueryable<T>将允许调用者在实际生成SQL代码之前进一步细化搜索条件。 性能方面,如果使用您的代码的开发人员在执行查询之前未应用任何过滤器,那么这只会是一个问题。 如果你足够信任它们给它们足够的绳索来挂起它们(并且可能会降低你的数据库性能),那么只返回IQueryable<T>可能就足够了。

如果您不信任它们,那么,正如其他人所指出的那样,您可以通过使用Skip()Take()扩展方法来实现简单的分页来限制查询返回的记录数,但请注意,它可以如果人们在进入下一页之前对数据库进行了更改,则记录会滑过裂缝。 与不断变化的数据库无缝地进行分页工作比很多人想象的要困难得多。

另一种方法是将GetAll()方法替换为需要调用者在返回结果之前应用过滤器的方法:

public IQueryable<T> GetMatching<T>(Expression<Func<T, bool>> filter)
{
  // Replace myQuery with Context.Set<T>() or whatever you're using for data access
  return myQuery.Where(filter);
}

然后像var results = GetMatching(x => x.Name == "foo");一样使用它var results = GetMatching(x => x.Name == "foo"); 或者你想做什么。 请注意,通过调用GetMatching(x => true)可以很容易地绕过这个,但至少它可以明确这个意图。 您还可以将此与第一种方法结合使用,以便对返回的记录数量设置固定上限。

但我个人的感觉是,所有这些限制查询的方法都只是针对不良开发人员开始使用您的应用程序的保险,如果您的项目开发人员不好,他们会找到一种方法来解决问题,无论如何你想做什么 所以我的投票只是返回一个IQueryable<T>并相信它会被负责任地使用。 如果有人滥用它,请取走GetAll()方法并为它们提供训练轮方法,如GetRecentPosts(int count)GetPostsWithTag(string tag, int count)或类似的东西,其中查询逻辑不在他们手中。


It depends on how your repository class is set up. If you're performing the query immediately, i.e. if your GetAll() method returns something like IEnumerable<T> or IList<T>, then yes, that could easily be a performance problem, and you should generally avoid that sort of thing unless you really want to load all records at once.

On the other hand, if your GetAll() method returns an IQueryable<T>, then there may not be a problem at all, depending on whether you trust the people writing queries. Returning an IQueryable<T> would allow callers to further refine the search criteria before the SQL code is actually generated. Performance-wise, it would only be a problem if developers using your code didn't apply any filters before executing the query. If you trust them enough to give them enough rope to hang themselves (and potentially take your database performance down with them), then just returning IQueryable<T> might be good enough.

If you don't trust them, then, as others have pointed out, you could limit the number of records returned by your query by using the Skip() and Take() extension methods to implement simple pagination, but note that it's possible for records to slip through the cracks if people make changes to the database before you move on to the next page. Making pagination work seamlessly with an ever-changing database is much harder than a lot of people think.

Another approach would be to replace your GetAll() method with one that requires the caller to apply a filter before returning results:

public IQueryable<T> GetMatching<T>(Expression<Func<T, bool>> filter)
{
  // Replace myQuery with Context.Set<T>() or whatever you're using for data access
  return myQuery.Where(filter);
}

and then use it like var results = GetMatching(x => x.Name == "foo");, or whatever you want to do. Note that this could be easily bypassed by calling GetMatching(x => true), but at least it makes the intention clear. You could also combine this with the first method to put a firm cap on the number of records returned.

My personal feeling, though, is that all of these ways of limiting queries are just insurance against bad developers getting their hands on your application, and if you have bad developers working on your project, they'll find a way to cause problems no matter what you try to do. So my vote is to just return an IQueryable<T> and trust that it will be used responsibly. If people abuse it, take away the GetAll() method and give them training-wheels methods like GetRecentPosts(int count) or GetPostsWithTag(string tag, int count) or something like that, where the query logic is out of their hands.

相关问答

更多
  • 这取决于您的存储库类的设置方式。 如果您正在立即执行查询,即如果您的GetAll()方法返回类似IEnumerable或IList ,那么是的,这可能很容易成为性能问题,您通常应该避免这种情况,除非你真的想一次加载所有记录。 另一方面,如果您的GetAll()方法返回IQueryable ,则可能根本没有问题,具体取决于您是否信任编写查询的人。 返回IQueryable将允许调用者在实际生成SQL代码之前进一步细化搜索条件。 性能方面,如果使用您的代码的开发人员在执行查询之前未应用任 ...
  • 7.0.0-rc1-final推荐的事务模式与7.0.0-rc1-final中的相同: using (var transaction = context.Database.BeginTransaction()) { try { /*do something*/ context.SaveChanges(); transaction.Commit(); } catch (Exception ex) { tr ...
  • var orders = db.Orders.Where(m => m.OrderItems.Any(i => i.OrderId == 5)).ToList(); var orders = db.Orders.Where(m => m.OrderItems.Any(i => i.OrderId == 5)).ToList();
  • 您可以将where子句传递给函数: 看到这个答案: C#Linq where子句作为变量 所以,你可以这样写: public IList ReadUsersWhere(Expression> whereClause) { return context.Users.Where(whereClause).ToList(); } 你会这样称呼它: foo.ReadUsersWhere(u => u.Name.Contains("Joe")); 但在那一点上,你 ...
  • 使用SQL Server探查器进行测试非常容易。 针对通用IdentityContext: int? id = 0; var user = db.Users.Find(id); Sql profiler结果: exec sp_executesql N'SELECT TOP (2) [Extent1].[Id] AS [Id], [Extent1].[Email] AS [Email], [Extent1].[EmailConfirmed] AS [EmailConfirmed ...
  • 我能够找到使用Entity Framework 6测试所有内容的推荐方法。此建议的资源可从http://msdn.microsoft.com/en-US/data/dn314431获得 。 简而言之,需要为需要测试的每个位创建测试类。 我最终做的是以下内容: TestDbSet.cs public class TestDbSet : DbSet, IQueryable, IEnumerable where TEntity : class { ...
  • IMO,谓词应该在你的ApplyFilter方法中(关注点)。 一种可能的编码方式是: public static IQueryable ApplyFilter(IQueryable items, IEnumerable enumValues, Expression> enumField) { return items.Where(i => enumValues. ...
  • 我通过下面的代码来解决我的问题: public int PostTestResultObj(List testandsampleresult) { long testResultId = 0; if (testandsampleresult != null) foreach (TestAndSampleResult orderdet in testandsampleresult) ...
  • 您需要将上下文传递给此方法,或者更好的是,传递宽度和高度,而不是传入大小对象本身。 You need to pass the context to this method, or, better yet, rather than pass in width and height, pass in the size object itself.
  • 它应该看起来像: from pa in db.personnelAllowedDates join pi in db.PersonnelInformation on pa.personelId equals pi.personelId select new AnObjectDefinedByYou { PersonelId = pa.personelId, AllowedDatesId = pa.allowedDatesId, //... PersonnelNumber = ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)