views:

144

answers:

1

I have the following code.

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)
                        });

I had to go the Anonymous type route as CodeDescription isn't a property of benefitCode and the customer wants it to appear this way in a dropDrownList. Anyways my question is how can I select a subset of items from this list? I need to select items based on the BenInterest attribute.

So this returns IEnumerable, so I am trying to go this route and this is where I get stuck. My intent is to build a new IEnumerable list and set a dropdown datasource to it.

 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
        }

So how do I create a new Enumerable of the same Anonymous type that only contains the desired items.

Thanks for any help. Cheers, ~ck

+2  A: 

You can just use:

var newCollection = bc.Where( e => e.BenInterest == 'E' );
Reed Copsey
Nope. This returns IEnumerable not IEnumerable<T>. Where is not supported. 'CodeDescription' is not a field in the table, so I get no type safety.
Hcabnettek
mmm - bc shoudl be an IEnumerable<T>, with T as your anonymous type. What "type" is Benefit codes? Is this using LINQ to SQL, Entity framework, etc? In any case, you can always make a class to hold this information, and construct it instead of using an anonymous type. Then you could use IEnumerable.Cast to turn it into IEnumerable<MyClass>
Reed Copsey
Yes LINQ to SQL. I didn't think of creating a class for this. That sounds like a great idea. I will use the same qry and just loop through my results and build a strongly typed list of what I need. Thanks for the idea.
Hcabnettek
Yeah - that's my suggestion. If you do that, life gets really easy - much easier than anonymous types in this case.
Reed Copsey