首页 > 解决方案 > 过滤字符串列表并仅选择多次出现的字符串的一次出现

问题描述

  var paymentTypes = _context
    .BursaryTransactions
    .Select(c => c.PaymentType)
    .ToList();

  string[] obj = paymentTypes
    .ToArray();

  var a = obj[1];

第一行从 Table 中检索以字符串形式存在的支付类型列表,BursaryTransactions第二行将列表转换为数组。

但是,第一行的列表包含类似的字符串,例如

  1. 发布 Utme
  2. 学费
  3. 学费
  4. 发布 Utme
  5. 表格
  6. 表格

我想过滤这些列表并只检索一次出现多次的项目。然后将新列表转换为数组。

标签: c#.netlinq

解决方案


您可以尝试GroupBy选择包含多个1项目的组:

   var result = _context
     .BursaryTransactions
     .GroupBy(c => c.PaymentType)        // Group By PaymentType
     .Where(group => group.Count() > 1)  // groups with more than 1 item
     .Select(group => group.First())     // we want just the 1st item of such group 
     .ToList();                          // materialized as a List<T>

编辑:删除重复项,我们可以First从每个项中获取项目group

   var result = _context
     .BursaryTransactions
     .GroupBy(c => c.PaymentType)
     .Select(group => group.First()) // First().PaymentType if you want PaymentType only
     .ToList();

推荐阅读