LINQ与查询不同

时间:2014-07-03 15:00:31

标签: c# sql linq

我有两个类的简单代码:

    public class Contact
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
        public DateTime DateOfBirth { get; set; }
        public string State { get; set; }
    }


    public class CallLog
    {
        public string Number { get; set; }
        public int Duration { get; set; }
        public bool Incoming { get; set; }
        public DateTime When { get; set; }
    }

现在在两个类中我有静态方法: SampleData(),其中我从源获取所有数据(SQL Server - 返回列表);

我的代码:

List<Contact> contacts = Contact.SampleData();
List<CallLog> callLogs = CallLog.SampleData();

现在我会得到数字,其中Incomming = true,Incomming = false(group by contact.Number)和电话号码所有者。

我写了这段代码:

var query = from contact in contacts
                        join callLog in callLogs on contact.Phone equals callLog.Number
                        group callLog by callLog.Number into g
                        select new
                        {
                            owner = Contact.SampleData().Where(c => c.Phone == g.Key).Take(1),
                            number = g.Key,
                            inCommingCall = callLogs.Where( c => c.Number == g.Key && c.Incoming == true).Count(),
                            outGoingCall = callLogs.Where( c=> c.Number == g.Key && c.Incoming == false).Count()
                        };
            foreach (var q in query)
            {
                foreach (var c in q.owner) Console.Write("owner = {0}, ", c.FirstName + " " + c.LastName);
                Console.WriteLine("number = {0}, in = {1}, out = {2}", q.number, q.inCommingCall, q.outGoingCall);
            }

看起来不错?

更好的查询:

var query = from contact in contacts
                        join callLog in callLogs on contact.Phone equals callLog.Number
                        group contact by new {contact.FirstName, contact.LastName, contact.Phone} into g
                        select new
                        {
                            owner = g.Key.FirstName + " " + g.Key.LastName,
                            inComming = callLogs.Where(c=>c.Number == g.Key.Phone && c.Incoming == true).Count(),
                            outGoing = callLogs.Where(c=>c.Number == g.Key.Phone && c.Incoming == false).Count()

1 个答案:

答案 0 :(得分:1)

var callsByContact = contacts.GroupJoin(callLogs, 
    c => c.Phone, 
    l => l.Number,
    (c, calls) => new { 
        Contact = c, 
        IncomingCalls = calls.Where(x => x.Incoming).ToList(), 
        OutgoingCalls = calls.Where(x => !x.Incoming).ToList()
    });

这应该按Number整理您的通话记录,然后列出该特定号码的所有来电/去电。