C#比较两个列表

背景:我有两个包含string的列表。 列出a和列表b。 此刻,我将Excel电子表格中的列表a的值写入列A,并将列表b的值写入列中。 列表b应该与列表a具有相同的数据并按顺序排列。 这并非总是如此。

问题:当我在Excel中写入List b的值时,如果它在列表a中的相同点,我想要写入单元格中的值,如果不是的话,我想写一个空string到单元格中。

编辑:感谢回复和答案工作得很好,只是意识到,我真正需要的是:

如果两个列表是:

a = {"a", "b", "c", "d", "e" } b = {"a", "d", "e" } 

操作的结果应该是:

 { "a", "", "", "d", "e" } 

一种方法是将列表zip在一起,并用空stringreplace列表b中的“错误”值:

 var a = new [] {"a", "b", "c", "d"}; var b = new [] {"a", "Foo", "c", "Bar"}; var fixed_b = a.Zip(b, (x, y) => x == y ? x : ""); 

fixed_b现在产生"a""""c"""

将数据写入Excel电子表格时,只需遍历fixed_b而不是b

编辑:

根据你的意见:

你可以创build一个像这样的小帮手方法:

 IEnumerable<T> FillBlanks<T>(IEnumerable<T> source, IEnumerable<T> collection, T blank) { using(var e = collection.GetEnumerator()) { bool more = e.MoveNext(); foreach(var x in source) if(more && x.Equals((T)e.Current)) { yield return x; more = e.MoveNext(); } else yield return blank; } } var fixed_b = FillBlanks(a, b, String.Empty); 
 int max = aList.Count > bList.Count ? aList.Count : bList.Count; for(int i = 0; i < max; ++i) { if(i < aList.Count) Write(aList[i]); if(i < bList.Count) { if(i < aList.Count) Write(aList[i] == bList[i] ? bList[i] : ""); else Write(bList[i]); } } 

这假设Write实际上写数据到电子表格。

尝试这个:

 class Program { static void Main(string[] args) { List<string> listA = new List<string>() { "a", "b", "c" }; List<string> listB = new List<string>() { "a", "c", "b" }; var result = listB.Select((b, index) => (index == listA.IndexOf(b)) ? b : ""); } }