Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Linq and the query of objects
Message
General information
Forum:
ASP.NET
Category:
Other
Miscellaneous
Thread ID:
01247883
Message ID:
01247892
Views:
18
I have found a lot of details on Linq, but have spent ZERO time with it.

Q. of the hour is "Can you query the collection and will Linq percolate through all objects within the container, or just what is visible in the container?

Case in point. You have a shopping cart collection of items that customer has picked. Can I create a statement that will find if any item has the Free Shipping flag = true? Or do I need to do a for each loop to define each object and do like is presently happening?

TIA


Short answer, yes, you can create a statement.

First, actually, you can do it NOW in VS2005 with the List class.

I have a different example, but you can apply it here. Suppose you have a collection of customers from a CustomerRec class, and you want to pull all those where the location is 1 or 2, and the amount due is > 5000.

You can use anonymous methods in C# in VS2005, and the FindAll method:
List<CustomerRec> oFilteredCustomers =
     oCustomerRecs.FindAll(
       (
          delegate(CustomerRec oRec)
          { 
             return ((oRec.LocationID == 1 
                    || oRec.LocationID == 2)
                        && oRec.AmountDue > 15000);
          }
        ));
The code uses the FindAll method of the list class to return a new collection of type CustomerRec.



Now, as for LINQ, the results of a LINQ query are an anonymous type - so if you want the results in a collection of the same type as your "source" collection, you'll need to add a line or two (unless there is an easier way that I'm not aware of).

First, let's create a method called GetCustomers, which will do the filtering, and return an IEnumerable....
public IEnumerable<CustomerRec>  GetCustomerResults() 
{

   IEnumerable<CustomerRec> oCustomerResults = 
        from oRecs in oCustomerRecs where
              ((oRecs.LocationID==1 || 
                oRecs.LocationID==2)
               && oRecs.AmountDue > 15000)
     orderby oRecs.LocationID ascending,
             oRecs.AmountDue descending
     select new customerRec ( element1, element2, etc.);

    return oCustomerResults;
}
Then you can call that method like so:
IEnumerable<CustomerRec> oResults = (IEnumerable<CustomerRec>)this.GetCustomerResults();
I have an article on LINQ in a recent issue of CoDe:
http://www.code-magazine.com/article.aspx?quickid=0707051&page=1


Let me know if that helps...

Kevin
Previous
Reply
Map
View

Click here to load this message in the networking platform