views:

121

answers:

1

the ToSelectList method I have:

public static IList<SelectListItem> ToSelectList<T>(this IEnumerable<T> itemsToMap, Func<T, string> textProperty, Func<T, string> valueProperty, Predicate<T> isSelected)
{
    var result = new List<SelectListItem>();

    foreach (var item in itemsToMap)
    {
        result.Add(new SelectListItem
        {
            Value = valueProperty(item),
            Text = textProperty(item),
            Selected = isSelected(item)
        });
    }
    return result;
}

when I call this method here:

    public static List<SelectListItem> lesgeverList(int selectedID) {
        NASDataContext _db = new NASDataContext();
        var lesg = (from l in _db.Lesgevers
                    where l.LG_Naam != "leeg"
                    orderby l.LG_Naam
                    select l).ToSelectList(m => m.LG_Naam + " " + m.LG_Vnaam, m => m.LG_ID.ToString(), m => m.LG_ID == selectedID);
        return lesg.ToList();
    }

the List<SelectListItem> I get has the selectedID as selected.

now, when I want to have multiple selected items, I give a list of Lesgevers

    public static List<SelectListItem> lesgeverList(List<Lesgever> lg) {
        NASDataContext _db = new NASDataContext();

        var test = (from l in _db.Lesgevers
                    where l.LG_Naam != "leeg" && lg.Contains(l)
                    orderby l.LG_Naam, l.LG_Vnaam
                    select l).ToList();

        var lesg = (from l in _db.Lesgevers
                    where l.LG_Naam != "leeg"
                    orderby l.LG_Naam, l.LG_Vnaam
                    select l).ToSelectList(m => m.LG_Naam + " " + m.LG_Vnaam, m => m.LG_ID.ToString(), m => lg.Contains(m));
        return lesg.ToList();
    }

the var test does return the Lesgevers that i have in the lg List, in my var lesg, there are no selectlistitem's selected at all.

where is my mistake? :) how do I fix thix?

+1  A: 

I assume that NASDataContext is a Linq-to-SQL or Linq-to-Entities data context.

In the var test selection, lg.Contains(l) is evaluated as part of the linq expressions, which means it will be translated into SQL and executed on the SQL server. That leaves it to the SQL server to determine equality for the contains statement. It will probably be converted to a WHERE IN (...) clause using the primary key of the Lesgever table.

In your ToSelectList method you are instead using object equality in the isSelected predicate. The items in the list will be fresh new objectes created by the data context. Even if they correspond to the same entity as the objects in the list lg, they will not be the same objects.

Try to adjust your predicate m => lg.Contains(m) to compare on the keys of the item, instead of the item object itself. Alternatively you can implement the IEquatable<T> interface to make isSelected use your own equality definition.

Anders Abel
if i work with the keys (int) then it does work as expected. thanks
Stefanvds