【问题标题】:How do I select a subset of items from an anonymous type IEnumerable?如何从匿名类型 IEnumerable 中选择项目子集?
【发布时间】:2010-11-21 10:39:07
【问题描述】:

我有以下代码。

MyDataContext db = MyDataContext.Create();
            bc =
                db.BenefitCodes.Select(
                    b =>
                    new
                        {
                            BenCd = b.BenCd
                            , Description = b.BenDesc
                            , BenInterest = b.BenInterest
                            , CodeDescription = string.Format("{0} - {1}", b.BenCd, b.BenDesc)
                        });

我不得不走匿名类型路线,因为 CodeDescription 不是 benefitCode 的属性,而客户希望它以这种方式出现在 dropDrownList 中。无论如何,我的问题是如何从该列表中选择项目的子集?我需要根据 BenInterest 属性选择项目。

所以这会返回 IEnumerable,所以我试图走这条路,这就是我卡住的地方。我的意图是构建一个新的 IEnumerable 列表并为其设置一个下拉数据源。

 IEnumerator enumerator = BenefitCodes.GetEnumerator(); 
        while(enumerator.MoveNext())
        {
              //What can I do here to return items based on BenInterest? 
              //I basically either want items that have a BenInterest of 'E'
              // or items that DO NOT have a BenInterest of 'E'
              // this is based on the value of a radioButtonList on the page
        }

那么我如何创建一个新的 Enumerable 相同的匿名类型,只包含所需的项目。

感谢您的帮助。 干杯, ~ck

【问题讨论】:

  • 您不能在调用 select 之前添加对 .Where() 函数的调用吗?

标签: c# linq-to-sql ienumerable yield ienumerator


【解决方案1】:

你可以使用:

var newCollection = bc.Where( e => e.BenInterest == 'E' );

【讨论】:

  • 不。这将返回 IEnumerable 而不是 IEnumerable。不支持的地方。 'CodeDescription' 不是表中的字段,所以我没有类型安全性。
  • mmm - bc 应该是一个 IEnumerable,T 是你的匿名类型。福利代码是什么“类型”?这是使用 LINQ to SQL、实体框架等吗?在任何情况下,您总是可以创建一个类来保存这些信息,并构造它而不是使用匿名类型。然后你可以使用 IEnumerable.Cast 把它变成 IEnumerable
  • 是的 LINQ to SQL。我没想过为此创建一个类。这听起来像一个好主意。我将使用相同的 qry 并遍历我的结果并构建我需要的强类型列表。感谢您的想法。
  • 是的 - 这是我的建议。如果你这样做了,生活就会变得非常轻松——在这种情况下,比匿名类型要容易得多。
猜你喜欢
  • 1970-01-01
  • 2012-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
相关资源
最近更新 更多