[英]Difference from one collection from another collection using Linq
I have two collections. 我有两个收藏。 First one is of complex type that contains two string properties
第一个是复杂类型,包含两个字符串属性
chpt_cd and appl_src_cd chpt_cd和appl_src_cd
public class ChapterCodeValidationOutput
{
public string chpt_cd { get; set; }
public string appl_src_cd { get; set; }
}
And it's get stored in a variable _validChapterCodeLst. 并将其存储在变量_validChapterCodeLst中。
It's sample data may look like : 它的样本数据可能看起来像:
chpt_cd aapl_src_cd
------- -----------
07038 C062
06206 C191
The input to the method that produces the collection is a collection of strings. 产生集合的方法的输入是字符串的集合。
List<string> _chapterCodes
that may contain data like : 可能包含以下数据:
'070038'
I want to find the difference between the two collection and put them in two separate lists accordingly. 我想找到两个集合之间的区别,并将它们分别放在两个单独的列表中。
Whichever is there in the _validChapterCodeLst should be the Valid Output List and it should have two columns likewise _validChapterCodeLst中的任何一个都应为有效输出列表,并且同样应具有两列
chpt_cd and associated appl_src_cd and the invalid list should contain the difference between _validChapterCodeLst and _chapterCodes input list. chpt_cd和关联的appl_src_cd以及无效列表应包含_validChapterCodeLst和_chapterCodes输入列表之间的差异。 And also should contain two columns likewise.
并且同样应该包含两列。
I tried 我试过了
gmvo._invalidChapterCodes = gmvi._chapterCodes.Except(_validChapterCodeLst.ConvertAll(x => x.chpt_cd.ToString())).ToList();
I tried to convert _validChapterCodeLst to List first and then perform Except. 我尝试先将_validChapterCodeLst转换为List,然后执行Except。
But that did not work . 但是那没有用。
Also I do not know how to get the associated appl_src_cd . 另外我也不知道如何获取相关的appl_src_cd。
Output should be 输出应为
06206 C191 06206 C191
Except
accepts only collections of the same type. Except
只接受相同类型的集合。 However, you can try this (I used HashSet
here for better performance): 但是,您可以尝试这样做(我在这里使用
HashSet
以获得更好的性能):
var _chapterCodesHashSet = new HashSet<string>(_chapterCodes);
var _invalidChapterCodes = _validChapterCodeLst.Where(item => !_chapterCodesHashSet.Contains(item.chpt_cd)).ToList();
I used where 我在哪里
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.