【问题标题】:Getting results from a List<T> C#从 List<T> C# 获取结果
【发布时间】:2013-07-05 02:13:57
【问题描述】:

我试图在对象列表中找到原始类型的代码并将结果放入新列表中。

我一直在 Google 中寻找类似的东西,但每个人都在谈论列表之间的交集,而我想要这样的东西。

            int AssocCode = 2;
            //Entity.ID
            //Entity.Name
            //Entity.AssociationCode
            List<Entity> list = new List<Entity>();
            list.Add(new Entity(1, "A", 1));
            list.Add(new Entity(2, "B", 2));
            list.Add(new Entity(3, "C", 3));
            list.Add(new Entity(4, "D", 2));
            list.Add(new Entity(5, "E", 2));

            /*I want the results for finding that code inside the collection**/
            List<Entity> newList = list .... find/intersect/select/remove/whatever (x => x.AssociationCode = AssocCode);

【问题讨论】:

  • 你已经有了它(在哪里),只需使用== 而不是=

标签: c# list select collections intersection


【解决方案1】:
int associationCode = 1;

List<Entity> newList = list.Where(e => e.AssociationCode == associationCode).ToList();

值得一提的是,如果您需要立即获得结果,您应该只致电ToList()

如果您不需要立即获得结果,这会更好。

IQueryable<Entity> entities = list.Where(e => e.AssociationCode == associationCode);

然后您可以进一步过滤而无需访问数据库。

【讨论】:

  • 好的,PeteGO。我看到你的修改有点晚了。但是你能告诉我 fullList = this.FullList.FindAll(item => item.AccCompanyID == CompanyCode); 有什么区别吗? vs fullList = this.FullList.Where(item => item.AccCompanyID == CompanyCode).ToList();谢谢你的回答!
  • 好吧,既然你有一个开始的列表(所有东西都加载了),我知道实际上并没有太大的区别。主要的是尝试仅在需要时加载您需要的内容,并且使用 IQueryable 和 linq 将为您完成此操作。当您调用 .ToList() 时,它会获取项目。
  • 感谢您的回答。我在这里找到了更多信息stackoverflow.com/questions/1938204/linq-where-vs-findall
【解决方案2】:

应该这样做:

var newList = list.Where(e => e.AssociationCode == AssocCode).ToList()

【讨论】:

    【解决方案3】:

    我在一分钟前解决了我的问题。像这样工作。

                List<Entity> newList =list.FindAll(item => item.AssociationCode == associationCode)
    

    但现在我看到你的答案 PeteGO 并且我测试过它也可以工作,但最后你是新添加这个 .ToList()

    现在我有点困惑。这2个有什么区别。

                fullList = this.FullList.FindAll(item => item.AccCompanyID == CompanyCode);
                vs
                fullList = this.FullList.Where(item => item.AccCompanyID == CompanyCode).ToList();
    

    【讨论】:

    • Where 构建查询并允许您添加其他约束和操作,例如 GroupByOrderBy。通过调用.ToList(),您是在询问您已完成构建查询以及您希望将数据检索到内存中的上下文。
    • 谢谢!我也在互联网上找到了这个补充信息。 stackoverflow.com/questions/1938204/linq-where-vs-findall
    猜你喜欢
    • 2018-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-27
    相关资源
    最近更新 更多