繁体   English   中英

使用Linq与一个收藏夹与另一个收藏夹的区别

[英]Difference from one collection from another collection using Linq

我有两个收藏。 第一个是复杂类型,包含两个字符串属性

chpt_cd和appl_src_cd

public class ChapterCodeValidationOutput
{
    public string chpt_cd { get; set; }
    public string appl_src_cd { get; set; }
}

并将其存储在变量_validChapterCodeLst中。

它的样本数据可能看起来像:

chpt_cd    aapl_src_cd
-------    -----------

07038      C062
06206      C191

产生集合的方法的输入是字符串的集合。

List<string> _chapterCodes 

可能包含以下数据:

'070038'

我想找到两个集合之间的区别,并将它们分别放在两个单独的列表中。

_validChapterCodeLst中的任何一个都应为有效输出列表,并且同样应具有两列

chpt_cd和关联的appl_src_cd以及无效列表应包含_validChapterCodeLst_chapterCodes输入列表之间的差异。 并且同样应该包含两列。

我试过了

gmvo._invalidChapterCodes = gmvi._chapterCodes.Except(_validChapterCodeLst.ConvertAll(x => x.chpt_cd.ToString())).ToList();

我尝试先将_validChapterCodeLst转换为List,然后执行Except。

但是那没有用。

另外我也不知道如何获取相关的appl_src_cd。

输出应为

06206 C191

Except只接受相同类型的集合。 但是,您可以尝试这样做(我在这里使用HashSet以获得更好的性能):

var _chapterCodesHashSet = new HashSet<string>(_chapterCodes);
var _invalidChapterCodes = _validChapterCodeLst.Where(item => !_chapterCodesHashSet.Contains(item.chpt_cd)).ToList();

我在哪里

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<ChapterCodeValidationOutput> _validChapterCodeLst = new List<ChapterCodeValidationOutput>() {
                new ChapterCodeValidationOutput() { chpt_cd =  "07038", appl_src_cd = "C062"},
                new ChapterCodeValidationOutput() { chpt_cd =  "06206", appl_src_cd = "C191"}
            };
            List<string> _chapterCodes = new List<string>() { "07038" };
            var results = _validChapterCodeLst.Where(x => !_chapterCodes.Contains(x.chpt_cd)).Select(y => new { chpt_cd = y.chpt_cd, appl_src_cd = y.appl_src_cd}).ToList();
        }
    }
    public class ChapterCodeValidationOutput
    {
        public string chpt_cd { get; set; }
        public string appl_src_cd { get; set; }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM