后台:我有两个包含字符串的列表。列出a和列表b。目前,我将excel电子表格中的List a的值写入A列,将List b的值写入Column。列表b应与列表a具有相同的数据并按顺序排列。情况并非总是如此。
问题:当我在Excel中写入列表b的值时,我想在单元格中写入值,如果它在同一点的列表a中,如果不是,我想写一个空字符串进入单元格。
编辑: 感谢回复和答案工作得很好,只是意识到我真正需要的是:
如果有两个列表:
a = {"a", "b", "c", "d", "e" }
b = {"a", "d", "e" }
操作的结果应该是:
{ "a", "", "", "d", "e" }
答案 0 :(得分:5)
一种方法是将zip
列表放在一起,并用空字符串替换列表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
修改强>
根据你的意见:
你可以像这样创建一个小帮手方法:
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);
答案 1 :(得分:1)
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
实际上将数据写入电子表格。
答案 2 :(得分:0)
试试这个:
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 : "");
}
}