List<t> findall question - predicates?

G

Guest

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
 
N

Nicholas Paldino [.NET/C# MVP]

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.
 
B

Ben Voigt

mgonzales3 said:
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*/

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top