【问题标题】:Filter a List of Strings and select only one occurance of a string with multiple occurance过滤字符串列表并仅选择一次出现多次出现的字符串
【发布时间】:2020-04-07 00:00:44
【问题描述】:
  var paymentTypes = _context
    .BursaryTransactions
    .Select(c => c.PaymentType)
    .ToList();

  string[] obj = paymentTypes
    .ToArray();

  var a = obj[1];

第一行检索来自BursaryTransactions 表的字符串中的付款类型列表 第二行将列表转换为数组。

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

  1. 发布 Utme
  2. 学费
  3. 学费
  4. 发布 Utme
  5. 第三形式
  6. 第三形式

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

【问题讨论】:

标签: c# .net linq


【解决方案1】:

你可以试试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>

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

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

【讨论】:

    【解决方案2】:

    你可以试试这个方法

    var result = _context.BursaryTransactions.GroupBy(c => c.PaymentType)
         .Where(g => g.Count() > 1)
         .Select(g => g.First())
         .ToArray();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-25
      • 1970-01-01
      • 2023-02-04
      • 2019-06-03
      • 2014-03-21
      相关资源
      最近更新 更多