none
"Group by" question RRS feed

  • Question

  • I am attempting to construct the proper LINQ statement to select multiple records and to sort them by "MessageType".  I am not understanding how to implement the "group by" because I seem only able to select the KEY field.  I will then construct an XML form with each messageType under its own tag including a count of the items within that tag.  Here is my code-in-progress snippet.  Can any offer a suggestion?

    var msgs =

    from msg in dc.GetTable<Message>()

    where msg.UserID == ID && msg.CompanyID == CompanyID

    group msg by msg.MsgType into gm

    select

    new { gm.Key,

    msg.DeliveredTime

    };

    count = msgs.Count();

    foreach (var m in msgs)

    {

    MessageType = m.MsgType;

    MessageID = m.MessageID;

    StringTime = m.DeliveredTime.ToString();

    MessageXML = BuildMessageXML(MessageID, StringTime, MessageType, count);

    return MessageXML;

    };

      
    Thursday, January 22, 2009 5:01 PM

All replies

  • Once you've done a group-by the only variable left in scope is the group variable 'gm'.  The group variable refers both to a key and a list of items that specified to put into the group.  You can't get at the members of the items of the group unless you do an operation over the group that allows to to access individual members (an aggregate operation like Min or Max for example.)

    The key of the group is the value you chose in the 'by' clause.  So if you are grouping by the message type, then the key is the messag type.

    If you just want to sort by message type, you may not need the group-by at all; you can just use order-by.

    from msg in dc.GetTable<Message>()
    where msg.UserID == ID && msg.CompanyID == CompanyID
    orderby msg.MsgType
    select msg;

    If, however, you wanted to write a query that tells you the earliest delivered time for all messages of the same type then you need group-by.

    from msg in dc.GetTable<Message>()
    where msg.UserID == ID && msg.CompanyID == CompanyID
    orderby msg.MsgType
    group msg by msg.MsgType into gm
    select new { MsgType = gm.Key,  EarliestTime = gm.Min(m => m.DeliveredTime) }


    Wayward LINQ Lacky
    Thursday, January 22, 2009 5:15 PM
    Moderator