如何从匿名类型IEnumerable中选择项目的子集?

时间:2009-08-20 18:55:26

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

我有以下代码。

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

1 个答案:

答案 0 :(得分:3)

你可以使用:

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