tags:

views:

97

answers:

6

i have this code:

  List<T> apps = getApps();

        List<int> ids;

        List<SelectListItem> dropdown = apps.ConvertAll(c => new SelectListItem
        {
            Selected = ids.Contains(c.Id),
            Text = c.Name,
            Value = c.Id.ToString()
        }).ToList();


ids.Contains

seems to always return false even though the numbers do match

any ideas?

+1  A: 

If you just need a true/false result

bool isInList = intList.IndexOf(intVariable) != -1;

if the intVariable does not exist in the List it will return -1

Bobby Borszich
`IndexOf` is zero-based. That should be `>= 0` :)
Frédéric Hamidi
Or really it should just check `!= -1` since the -1 return value is defined as the negative result.
Daniel DiPaolo
thanks for the comments, good points
Bobby Borszich
+1  A: 

As long as your list is initialized with values and that value actually exists in the list, then Contains should return true.

I tried the following:

var list = new List<int> {1,2,3,4,5};
var intVar = 4;
var exists = list.Contains(intVar);

And exists is indeed set to true.

Rune Grimstad
OP updated his question which you answer. his ids list does not appear to be initialized. Shouldn't that be a compiler catch?
SB
Yeah. An uninitialized list should cause a compiler error. But not if the list is defined at class level, then it will be initialized to null and the compiler will be happy.
Rune Grimstad
A: 

The way you did is correct. It works fine with that code: x is true. probably you made a mistake somewhere else.

List<int> ints = new List<int>( new[] {1,5,7});
var i = 5;
var x = ints.Contains(i);
gsharp
A: 

You should be referencing Selected not ids.Contains as the last line.

I just realized this is a formatting issue, from the OP. Regardless you should be referencing the value in Selected. I recommend adding some Console.WriteLine calls to see exactly what is being printed out on each line and also what each value is.

After your update: ids is an empty list, how is this not throwing a NullReferenceException? As it was never initialized in that code block

Woot4Moo
A: 

Here is a extension method, this allows coding like the SQL IN command.

public static bool In<T>(this T o, params T[] values)
{
    if (values == null) return false;

    return values.Contains(o);
}
public static bool In<T>(this T o, IEnumerable<T> values)
{
    if (values == null) return false;

    return values.Contains(o);
}

This allows stuff like that:

List<int> ints = new List<int>( new[] {1,5,7});
int i = 5;
bool isIn = i.In(ints);

Or:

int i = 5;
bool isIn = i.In(1,2,3,4,5);
Dennis
A: 
bool vExist = false;
int vSelectValue = 1;

List<int> vList = new List<int>();
vList.Add(1);
vList.Add(2);

IEnumerable vRes = (from n in vListwhere n == vSelectValue);
if (vRes.Count > 0) {
    vExist = true;
}
sv88erik