开发者

I just don't understand how to use Linq

I have a class as follows:

Class Scan
    Delivered As Boolean
    ScanDate As Date
    State As String
    Facility As String  
End Class

I then create a list and populate it with scans containing whatever.

Dim Scans As New List(Of Scan) 

I need to mine the list to get various pieces of information. I would like to use LINQ to do it. The problem is that for the life of me, I just don’t get it. The syntax throws me off, the fact that the results are not strongly typed throws me off, and the sample on the web are oversimplified, or overcomplicated.

How could I

  1. Get a count of scans, grouped by Date where Delivered = True
  2. Get a count of scans, grouped by Facility where Delivered = True
  3. Get a count of scans, grouped by State where Delivered = True

I then want to use this in a For Each loop.

For Each result In GroupedResults
    ‘My Code

Next

Ideally, I’d like the result to be strongly typed. Is this possible?

Can anyone recommend some links to get started with this? Every web site I come across just gets my head swimming. I’m not understanding it at all.

EDIT:

Thank you so much guys. I’m still scra开发者_开发技巧tching my head over this stuff , but at least this is a real world example I can use to get an idea of what is going on.

I was hoping that this simple example would help me spring board into a more complex use – no luck yet. I should have asked this off the bat.

All the examples seem to use a key/value response. What if I have two values I need grouped?

    Class Scan
        Delivered As Boolean
        Scanned As Boolean
        ScanDate As Date
        State As String
        Facility As String  
    End Class


1. Get a count of Delivered = True,  a count  of Scanned=True, grouped by Date 
2. Get a count of Delivered = True,  a count  of  Scanned=True, grouped by Facility 
3. Get a count of Delivered = True,  a count  of Scanned=True, grouped by State 

Is it possible to get this in one result?

Edit Edit:

Answered my own Edit! This seems to be working for me:

Dim query = From r In scans _
            Group r By r.ScanDate Into g = Group _
            Select New With _
            {g, .DeliveredCount = g.Count(Function(s) s.Delivered), .ScannedCount = g.Count(Function(s) s.Scanned)}

Thank you so much guys. You got me to the point where I could hack a solution out. I still don’t “get” what I’m doing (What is Function(s)?!), but I’ve got something to start with. I intend to spend time learning this now. I think what really threw me off is that the samples on the net are C#. Normaly I have no problem converting the syntax, but with LINQ this is not as simple. I thought I was doing something wrong, but it was just that the syntax was very different.


You are not limited of using LINQ's query syntax. You can also use the LINQ extension methods on the collections.

The result that you'll receive will be strongly typed. Although anonymous types will be used when you do not return an existing type.

The code below is C#, but you'll understand:

static void Main( string[] args )
{
    List<Scan> scans = new List<Scan> ();

    scans.Add (new Scan (new DateTime (2010, 1, 1), true, "Facility1"));
    scans.Add (new Scan (new DateTime (2010, 1, 1), true, "Facility2"));
    scans.Add (new Scan (new DateTime (2010, 1, 1), false, "Facility3"));
    scans.Add (new Scan (new DateTime (2010, 1, 26), true, "Facility1"));

    var result1 = scans.Where (s => s.Delivered).GroupBy (s => s.ScanDate);

    foreach( var r in result1 )
    {
        Console.WriteLine (String.Format ("Number of delivered scans for {0}: {1}", r.Key, r.Count ()));
    }

    var result2 = scans.Where (s => s.Delivered).GroupBy (s => s.Facility);

    foreach( var r in result2 )
    {
        Console.WriteLine (String.Format ("Number of delivered scans for {0}: {1}", r.Key, r.Count ()));
    }

    Console.ReadLine ();

}

The result here is not really typed, since a GroupBy expression returns an IGrouping type. However, you can get around this, by doing this:

 var result2 = scans.Where (s => s.Delivered)
                    .GroupBy (s => s.Facility)
                    .Select( s => new { Facility = s.Key, NumberOfItems = s.Count() } );

Using the extension methods that LINQ provides, may perhaps help you understanding it a bit more.

Sorry for the C# syntax, but I'm not really familiar with VB.NET.


Dim GroupedResults = from s in Scans _
                     where Delivered _
                     group s by ScanDate into g //edit here for the others _
                     select new { Category = g.Key, ScanCount = g.Count() };

apologies if the c# to vb conversion is wrong!


I came across much the same confusion. I agree that the documentation is not very clear. I now use LINQ in three projects, and I rather like it.

If you're using LINQ to SQL, create your LINQ class by creating a connection to your server in Server View and dragging your table across into your Data Context. Otherwise, just set db as the collection of your Scan objects.

1) Get a count of scans, grouped by Date where Delivered = True

Dim db = new BrettsDataContext
Dim Query = From s as Scan in db _
Where s.Delivered = True _
Order By s.Date

2) Get a count of scans, grouped by Facility where Delivered = True

Dim db = new BrettsDataContext
Dim Query2 = From s as Scan in db _
Where s.Delivered = True _
Order By s.Date

3) Get a count of scans, grouped by State where Delivered = True

Dim db = new BrettsDataContext
Dim Query3 = From s as Scan in db _
Where s.Delivered = True _
Order By s.State

That last one will get all the result rows. If you just want the count as a number:

Dim count = (From s as Scan in db _
Where s.Delivered = True).Count

If you wanted all the separate Delivery Dates, you could do the following query:

Dim db = new BrettsDataContext
Dim Query4 = From s as Scan in db _
Where s.Delivered = True _
Order By DeliveryDate

To set as a data source, just do the following:

Dim db = new BrettsDataContext
Dim Query = From s as Scan in db _
Where s.Delivered = True _
Order By s.Date

gridview1.DataSource = Query

Hope this helps!


If you would like to use LINQ I would suggest reading this page on using LINQ with Objects (such as your own class Scan):

http://msdn.microsoft.com/en-us/library/bb397937.aspx

It should be straightforward enough to understand without causing your head to spin. :)

Otherwise, I would suggest using the List class itself which has many helpful functions. Check here for information about that:

http://msdn.microsoft.com/en-us/library/d9hw1as6.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜