FrenkyB FrenkyB - 29 days ago 5
C# Question

ListItemCollection - get text from value with LINQ

I have

ListItemCollection
. Each element is of type
ListItem
. 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?

Answer

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.

Comments