FrenkyB FrenkyB - 7 months ago 38
C# Question

ListItemCollection - get text from value with LINQ

I have

. Each element is of type
. I want to return only text with item that has value given.

For now, I am using this function:

public string GetTextFromPaymentWayCollection(string value)
ListItemCollection listPaymentWays = DB.GetList();

foreach (ListItem item in listPaymentWays)
if (item.Value == value)
return item.Text;
return null;

Is there a way to do this with LINQ, instead of using this function?


Your listPaymentWays is of ListItemCollection that does not implement IEnumerable<T>. The linq methods are extension methods on IEnumerable<T>.

For example the signature of FirstOrDefault:

public static TSource FirstOrDefault<TSource>(
    this IEnumerable<TSource> source

What you should do is first Cast (which will return an IEnumerble<ListItem>) and then use the FirstOrDefault:

var result = listPaymentWays.Cast<ListItem>()
                            .FirstOrDefault(x => x.Value == value)?.Text;

The ?. is C# 6.0 Null Proparation feature.

Also I'd recommend that DB.GetList() will expose a method that will get the value so the filtering will happen in the database and not in memory. It is a waste to bring all the data, create ListItems of it to then just take a single item.