使用LINQ的列表中的不同项目

时间:2018-03-16 20:22:25

标签: c# linq distinct-values

我有以下课程:

public class CustomerDTO
    {
            public string CardNumber { get; set; }
            public string CustomerNumber { get; set; }        
            public DateTime FetchedDate { get; private set; } = DateTime.Now;
    }

此类将被添加到List中

    var duplicateCustomers = new List<CustomerDTO>
                {
                    new CustomerDTO { CardNumber = "123456", CustomerNumber = "1234" },
                    new CustomerDTO { CardNumber = "123456", CustomerNumber = "1234" },
                    new CustomerDTO { CardNumber = "654321", CustomerNumber = "4321" },
                    new CustomerDTO { CardNumber = "654321", CustomerNumber = "4321" }
                };

我想要实现的是将此列表过滤为不同的项目,因此只需要四个项目中的两个&amp;确保重复条目的FetchedDate字段是MAX。

所以上面列表中的所有4个项目如下所示:

  • 123456,1234,2018-03-16 20:17:001
  • 123456,1234,2018-03-16 20:17:002
  • 654321,4321,2018-03-16 20:17:003
  • 654321,4321,2018-03-16 20:17:004

然后当这个列表被过滤时(可能使用扩展方法),它将如下所示:

  • 123456,1234,2018-03-16 20:17:002
  • 654321,4321,2018-03-16 20:17:004

有人可以告诉我如何实现这个目标吗?

3 个答案:

答案 0 :(得分:0)

尝试使用GroupBy

duplicateCustomers = duplicateCustomers.GroupBy(item => new 
{
    CardNumber = item.CardNumber,
    CustomerNumber = item.CustomerNumber
})
.Select(item => new CustomerDTO()
{
    CardNumber = item.Key.CardNumber,
    CustomerNumber = item.Key.CustomerNumber,
    FetchedDate = item.Max(m => m.FetchedDate)
})

答案 1 :(得分:0)

试试这个:

var results = duplicateCustomers
     .GroupBy(c => new { c.CardNumber, c.CustomerNumber })
     .Select(d => d.OrderByDescending(e => e.FetchedDate)
     .First())
     .ToList();

基本上我在这里做的是使用GroupBy根据两个属性CardNumber和CustomerNumber在列表中选择不同的项目。然后在项目结果中选择第一个结果。

答案 2 :(得分:0)

您可以尝试以下适合您要求的代码

 static void Main(string[] args)
        {
            var duplicateCustomers = new List<CustomerDTO>
                {
                    new CustomerDTO { CardNumber = "123456", CustomerNumber = "1234" },
                    new CustomerDTO { CardNumber = "123456", CustomerNumber = "1234" },
                    new CustomerDTO { CardNumber = "654321", CustomerNumber = "4321" },
                    new CustomerDTO { CardNumber = "654321", CustomerNumber = "4321" }
                };
           // var nonduplicates= duplicateCustomers.Distinct(x => x.).ToList();//duplicateCustomers.Select(x => x.CustomerNumber).Distinct().ToList();
            List<CustomerDTO> distinctCustomers = duplicateCustomers
   .GroupBy(p => p.CardNumber)
   .Select(g => g.FirstOrDefault())
   .ToList();
            foreach (var item in distinctCustomers)
            {
                Console.WriteLine("Details  "+item.CardNumber +" "+ item.CustomerNumber + "   "+item.FetchedDate);
                //Console.WriteLine("cust Number" + item.CustomerNumber);
            }

            Console.ReadLine();
        }