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?
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.
You need to Cast it first to use Where
. The rest is just ordinary Linq.
string s = listPaymentWays.Cast<ListItem>()
.ToDictionary(i => i.Value, i => i.Text)
.Where(x => x.Value == value)
.FirstOrDefault().Value;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With