tags:

views:

81

answers:

1
+1  Q: 

Linq Group By

I have a abstract Class where a Recipient either can be a EMailRecipient or a SMSRecipients.

Im selecting the data out in a List like List<Recipient>. For statistic reason i need to know then number of recipients based on the CountryCode in the SMSRecipient and i thought i could do that in linq. But i cant seem to cast a Recipient as a SMSRecipient like

var q = from v in AMessageQueueContentList
        group v by (FlexyNet.Data.SMSRecipient)v.Recipient into g
        select count(g);

My class looks like this:

public abstract class Recipient
{
    public int MemberID { get;set;}
    public Recipient(){}
}

public class EMailRecipient : Recipient
{
    public string EMail { get; set; }
    public bool ValidMail { get; set; }

    public EMailRecipient(FlexyDataReader read)
    {
        this.MemberID = (int)read["MemberID"];
        this.EMail = (string)read["Recipient"];
    }

    public EMailRecipient(int memberID,string eMail)
    {
        this.MemberID = memberID;
        this.EMail = (string)eMail;
    }


}

public class SMSRecipient : Recipient
{
    public string Number { get; set; }
    public string CountryCode { get; set; }
    public nimta.Recipient NimtaRecipient { get; set; }
}
+2  A: 

Could you do something like this?

var counts = from m in AMessageQueueContentList
             let s = m.Recipient as FlexyNet.Data.SMSRecipient
             where s != null
             group s by s.CountryCode into g
             select new { CountryCode = g.Key, Count = g.Count() };

Or if you actually have a list of Recipient objects, you could use LINQ's OfType<T>() extension method:

var sms = recipients.OfType<FlexyNet.Data.SMSRecipient>();
var counts = from s in sms
             group s by s.CountryCode into g
             select new { CountryCode = g.Key, Count = g.Count() };
dahlbyk