【问题标题】:How to match string in 2 diff collection and return the collection items that did not match in LINQ如何在 2 diff 集合中匹配字符串并返回在 LINQ 中不匹配的集合项
【发布时间】:2013-10-09 09:38:37
【问题描述】:

我有 2 个不同类型的集合。我想匹配那些集合中的一个字符串并返回不匹配的集合。

1) ac_CategoryList
2) mw_CharityList

如果 ac_CategoryList.Title 存在于 mw_CharityList.EntryTitle 中,则希望匹配。如果不存在,则返回不匹配的 ac_CategoryList 集合项。并返回一个在 ac_CategoryList.Title 中匹配的 mw_CharityList 类型的集合。因为我需要更新 mw_CharityList 集合中的状态。

var var charityList = _db.mw_CompetitionsEntry.Where(e => e.IsInvalid == false && e.IsPublished).ToList(); // first get the entire valid collection
var categoryList = _db.ac_Category.Where(c => c.Title != null && c.IsDeleted == false).ToList(); // get the entire valid collection

var titleNotExitsCollection = categoryList.Where(c => charityList.Any(e => e.EntryTitle.Trim() != c.Title.Trim())).ToList();
var titleExitsCollection = charityList.Where(e => categoryList.Any(c => c.Title.Trim() == e.EntryTitle.Trim())).ToList();

现在 titleNotExitsCollection 和 titleExitsCollection 返回相同的记录数。我不知道我做错了什么...请帮助

【问题讨论】:

    标签: c# asp.net linq c#-4.0 lambda


    【解决方案1】:

    好像少了一个非运算符,试试:

    var titleNotExitsCollection = categoryList.Where(c => !charityList.Any(e => e.EntryTitle.Trim() == c.Title.Trim())).ToList();
    

    【讨论】:

    • +1 - 简洁明了,但不确定如果任一列表包含 nuuls 将如何工作
    【解决方案2】:
    var commonTitles = categoryList.Select(x=>x.Title.Trim())
                                   .Intersect(charityList.Select(x=>x.EntryTitle.Trim()));
    var titleNotExitsCollection  = categoryList.Where(x=>!commonTitles.Contains(x.Title))
                                               .ToList();
    var titleExitsCollection = charityList.Where(x=>commonTitles.Contains(x.EntryTitle))
                                          .ToList();
    

    【讨论】:

      猜你喜欢
      • 2017-05-16
      • 2019-11-30
      • 2019-11-13
      • 1970-01-01
      • 2016-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多