I am returning IList from Business layer. But in viewmodel I have to use Find function. One method is to convert IList to List.
But is there anyway to add "Find" method to IList
I am returning IList from Business layer. But in viewmodel I have to use Find function. One method is to convert IList to List.
But is there anyway to add "Find" method to IList
Well, there are the Linq extension methods .Where
(to fecth all that match) and .FirstOrDefault
(to fetch the first match) or you can write your own extension method against IList like:
public static class IListExtensions
{
public static T FindFirst<T>(this IList<T> source, Func<T, bool> condition)
{
foreach(T item in source)
if(condition(item))
return item;
return default(T);
}
}
you can use Where method
list.Where(predicate).First()
Can you use the IndexOf method?
very simple, just you need
casting step
var myModelasList= IListReturnedViewModel as List<ViewModelObject>;
//now you can use list feaures like Find Func.
myModelasList.Find((t => t.SomeFiald== currentState && t.IsSomting == somesymbol);
I wrote an extension method to do the casting for me.
public static T Find<T>(this IList<T> ilist, Predicate<T> match)
{
if (ilist is List<T> list)
{
return list.Find(match);
}
else if (ilist is T[] array)
{
return Array.Find(array, match);
}
else
{
return ilist.FirstOrDefault(i => match(i));
}
}
© 2022 - 2024 — McMap. All rights reserved.