Mikee
Mikee

Reputation: 1651

How Can I Concat 2 SelectList lists?

I need to combine 2 SelectLists into one, Concat() wants a cast that I can't figure out.

SelectList sl1 = new SelectList(Cust.GetCustListOne(), "Id", "Last", 2);
SelectList sl2 = new SelectList(Cust.GetCustListTwo(), "Id", "Last", 4);
SelectList sl3 = sl2.Concat(sl1);

The error for line 3 is CS0266 Cannot implicitly convert type IEnumerable to SelectList. An explicit conversion exists (are you missing a cast?)

Casting as follows

SelectList sl3 = (SelectList)sl2.Concat(sl1);

fails with the following error

InvalidCastException: Unable to cast object of type <ConcatIterator>d__59-1[System.Web.Mvc.SelectListItem] to type System.Web.Mvc.SelectList

What cast am I missing here?

Upvotes: 1

Views: 1442

Answers (3)

Sevleena B Joy
Sevleena B Joy

Reputation: 1

SelectList sl3 = new SelectList(sl2.Concat(sl1)); 

returned the SelectList with

SelectListItem.Text ='System.Web.Mvc.SelectListItem' 

and

SelectListItem.Value = null.

SelectList sl3 = new SelectList(sl2.Concat(sl1), "Value", "Text"); 

solved this issue for me.

Upvotes: 0

Prince Trotman
Prince Trotman

Reputation: 59

Use .union on both SelectLists

    List<person> persons = new List<person>();
    persons.Add(new person() { id = 1, name = "Abel" });
    persons.Add(new person() { id = 1, name = "Joseph" });

    List<person> persons2 = new List<person>();
    persons2.Add(new person() { id = 1, name = "Stacey" });
    persons2.Add(new person() { id = 1, name = "John" });

    SelectList s1 = new SelectList(persons);
    SelectList s2 = new SelectList(persons2);
    SelectList s3 = new SelectList(s1.Union(s2));

Upvotes: -1

Orel Eraki
Orel Eraki

Reputation: 12196

This is because System.Linq.Enumerable.Concat returns IEnumerable and as the error implies, it can not implicitly convert it to something it doesn't have conversion of.

Change:

SelectList sl3 = sl2.Concat(sl1);

To the following, which work, because SelectList constructor accepts IEnumerable

SelectList sl3 = new SelectList(sl2.Concat(sl1));

Upvotes: 3

Related Questions