过滤字符串列表并仅选择多次出现的字符串的一次出现

Ant*_*ony 0 .net c# linq

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

  string[] obj = paymentTypes
    .ToArray();

  var a = obj[1];
Run Code Online (Sandbox Code Playgroud)

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

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

  1. 乌特梅邮报
  2. 学费
  3. 学费
  4. 乌特梅邮报
  5. 形式
  6. 形式

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

Dmi*_*nko 5

您可以尝试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>
Run Code Online (Sandbox Code Playgroud)

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

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