![](/img/trans.png)
[英]Using LINQ to find all keys from one collection that are not in another?
[英]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.