1

I'm trying to write simple extension method for SelectList. API confuses me.

public static SelectList Without(this SelectList selectList,int val){
  //return new SelectList(selectList.Items.Where(x=>x.Value!=val)); <-----???
}

It should return new select list with same items w/o one which value matches argument val.

2
  • 1
    Could you expand on which bit of your method is not working? Commented Mar 14, 2011 at 9:29
  • @Mark selectList.Items.Where(x=>x.Value!=val) because Items.GetType==typeof(IEnumerable) Commented Mar 14, 2011 at 9:32

3 Answers 3

1
 public static class SelectListExtensions{
    public static SelectList Without(this SelectList selectList,params int[] what){
      var items=selectList.Items.Cast<SelectListItem>()
        .Where(x=>!what.Any(z=>int.Parse(x.Value)==z)).ToList();
      return new SelectList(items);
    }
    public static SelectList Without<T>(this SelectList selectList,params T[] what) where T:Enumeration{
      var items=selectList.Items.Cast<SelectListItem>()
        .Where(x=>!what.Any(z=>int.Parse(x.Value)==z.Value)).ToList();
      return new SelectList(items);
    }
  }

Only problem is - it assumes that Items will always contain IEnumerable<SelectListItem>.

Will be fine for me.

Sign up to request clarification or add additional context in comments.

Comments

0

Do you just need to apply a ToArray() to your IEnumerable collection??

return new SelectList(selectList.Items.Where(x=>x.Value!=val).ToArray());

2 Comments

Nope. Commented below my question. Problem is that Items is collection from objects. x does not have Value.
@Arnis. Ah, okay. Disregard my answer then. I have voted up your answer instead.
0
return new SelectList(selectList.Items.Cast<T>().Except(what));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.