Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ListItemCollection - get text from value with LINQ

Tags:

c#

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?

like image 456
FrenkyB Avatar asked Nov 04 '16 15:11

FrenkyB


2 Answers

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.

like image 147
Gilad Green Avatar answered Nov 14 '22 21:11

Gilad Green


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;
like image 33
VDWWD Avatar answered Nov 14 '22 21:11

VDWWD