【问题标题】:LINQ filter list based on given conditions基于给定条件的 LINQ 过滤器列表
【发布时间】:2021-10-07 14:56:48
【问题描述】:

我目前正在开发一个 .NET 应用程序。我需要编写一个 LINQ 查询来过滤下面示例中给出的List<SearchResult>

允许CompanyId + ContactIdCompanyId(无ContactId)的组合作为结果的键,结果列表中的条目必须不同

结果列表中的键是唯一的“CompanyID + ContactId”或唯一的“CompanyID”的组合。例如,在作为键的结果列表中,我可以有一个“companyID 1”和几个“companyID 1”+ ContactID (1, 2, 3, ...) 但每个 ContactID 只能与一个 CompanyID 组合一次即{1},{1, 1}, {1, 2}, {1, 3},但不是第二次{1, 1}{1}

public class SearchResult
{
    public int? CompanyId {get; set;}
    public int? ContactId {get; set;}
}

public class Program
{
    public static void Main()
    {
        var searchResults = new List<SearchResult>
        {
            new SearchResult { CompanyId = 1, ContactId = 1 }, // yes
            new SearchResult { CompanyId = 2, ContactId = 3 }, // yes
            new SearchResult { CompanyId = 2, ContactId = 4 }, // yes
            new SearchResult { CompanyId = 1 }, // yes
            new SearchResult { CompanyId = 2 }, // yes
            new SearchResult { CompanyId = 1, ContactId = 1 }, // no
            new SearchResult { CompanyId = 1 }, // no
            new SearchResult { }, // no
            new SearchResult { CompanyId = null }, // no
            new SearchResult { CompanyId = null, ContactId = null }, // no
            new SearchResult { ContactId = null }, // no
        };
        
        // Unfortunately my LINQ query doesn't work correctly 
        var result = searchResults
                      .GroupBy(sr => sr.CompanyId)
                      .Select(grp => grp.First());
        
        foreach(SearchResult sr in result){         
            Console.WriteLine(sr.CompanyId + " " + sr.ContactId);
        }
    }
}

我当前的 LINQ 查询不能正常工作 - 它也很基本。我只得到结果:[{1, 1},{2, 3}],真的很棘手。

虽然想要的结果应该是[{1, 1},{2, 3},{2, 4}, {1},{2}]

你知道如何检索正确的结果吗?

【问题讨论】:

  • 列表本身或更大级别的不同值?所有公司 ID 都应该是唯一的吗?
  • 为什么是new SearchResult { CompanyId = 1, ContactId = 1 }, // no - 处理是否依赖于项目的顺序?
  • 在更大的层面上 - 关键是唯一的“CompanyID + ContactId”或唯一的“CompanyID”的组合......所以在列表中我可以有一个 companyID 1 和几个 companyID 1 + ContactID (1, 2, 3, ... 但每个 ContactID 只有一次)
  • new SearchResult { CompanyId = 1, ContactId = 1 },重复 - 已经有另一个具有相同 CompanyId 和 ContactId 的条目
  • 哎呀,我的错...它已被删除:)

标签: c# .net linq


【解决方案1】:

非常接近,但是 .GroupBy CompanyIdContactId(而不仅仅是 CompanyId)然后使用 .First() 获取非骗子。

var result = searchResults
    .GroupBy(sr => new { sr.CompanyId, sr.ContactId })
    .Select(x => x.First());

【讨论】:

  • 感谢这完美的作品!我其实很接近哈哈。
  • @Bender。别客气! :)
猜你喜欢
  • 2015-11-18
  • 1970-01-01
  • 1970-01-01
  • 2018-06-12
  • 2010-10-22
  • 2022-12-15
  • 2021-07-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多