LINQ不同于查询

本文关键字:查询 不同于 LINQ | 更新日期: 2023-09-27 18:11:23

我有两个类的简单代码:

    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-return List(;

我的代码:

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

现在我会得到Incoming=true和Incoming=false的号码(按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()

LINQ不同于查询

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整理您的通话记录,然后为您提供该特定号码的所有来电/呼出电话列表。