I have a List<t> object consisting of objects which in themselves consist of
BindingListViews of objects. When I want to search for a object value I
normally create a foreach loop and increment a counter to provide me a count.
How can I refactor the same function w/o the foreach and use findall instead?
faux data structure:
---------------------
->
| Customers
<t> Orders
| Orders_Details
->
/*start code*/
foreach (Orders _o in _Customers.Orders)
{
if (_o.exists)
i = i + 1;
}
if (i == _Customers.Orders.Count)
mRet = true;
/*end code*/
/*start desired code*/
myList.findall(_o.quantity >1)
/*end desired code*/
I want to take advantage of the Findall method in the generics namespace.
thanks
Nicholas Paldino [.NET/C# MVP] - 22 May 2007 21:38 GMT
What is the call to exits on _o? From this code segment,
foreach (Orders _o in _Customers.Orders)
{
if (_o.exists)
i = i + 1;
}
if (i == _Customers.Orders.Count)
mRet = true;
The equivalent using FindAll is:
// See where the orders exists.
List<T> results = _Customers.Orders.FindAll(delegate(Orders _o) { return
_o.exists; });
// If the count is the same between the two, then set mRet = true.
if (_Customers.Orders.Count == results.Count)
// Set mRet to true.
mRet = true;
Of course, if you were setting mRet to false in the event that the count
was not equal, you could just do this:
mRet = (_Customers.Orders.FindAll(delegate(Orders _o) { return
_o.exists; }).Count == _Customers.Orders.Count);
Hope this helps.

Signature
- Nicholas Paldino [.NET/C# MVP]
- mvp@spam.guard.caspershouse.com
>I have a List<t> object consisting of objects which in themselves consist
>of
[quoted text clipped - 33 lines]
>
> thanks
Ben Voigt - 23 May 2007 00:35 GMT
>I have a List<t> object consisting of objects which in themselves consist
>of
[quoted text clipped - 23 lines]
> mRet = true;
> /*end code*/
This can be made faster in many cases by leaving the loop early:
foreach (Orders _o in _Customers.Orders)
{
if (!_o.exists)
return false;
}
return true;
To get the same result using a predicate, use List<T>.TrueForAll...
mRet = _Customers.Orders.TrueForAll(delegate (Orders o) { return
o.exists; });
BTW, it's usually considered bad practice to use names starting with
underscores, although this maybe isn't as important in C# because there's no
macro substitution possible.