问题描述
我正在尝试将编译后的字符串列表与主列表进行比较,然后将它们打印到文本文件中.我遇到的问题是可打印列表仍然为空.如何填充第三个列表?而且,这是否正确使用了List<>
,如果不是,我应该使用什么?
I'm trying to compare a list of strings compiled together against a master list and print them out to a text file. The problem I'm having is the printable list remains empty. How do I populate the third list? And, is this a proper use of List<>
, if not, what should I use?
编辑:很抱歉,在运行此方法之前,textInput
和textCompare
从两个文件中读取并填充了7个字符的字符串:一个是从文本文件中提取的,另一个来自Excel工作表.然后,我删除所有空值,并尝试将两个列表与listA.intersects(listB)
进行比较. MSDN提到要使相交起作用,需要对其进行枚举,这就是为什么我将其放在foreach中的原因.
Edit: Sorry about that, prior to this method running, textInput
and textCompare
read from two files and are populated with strings 7 characters in length: one pulled from a text file, the other from an excel sheet. I then remove any nulls, and attempt to compare the two lists with listA.intersects(listB)
. MSDN mentioned it need to be enumerated through for the intersects to work, which is why I put it in a foreach.
void Compare()
{
List<string> matches = new List<string>();
textInput.Sort();
textCompare.Sort();
progressBar.Maximum = textInput.Count;
int increment = 0;
for (int i = textCompare.Count - 1; i >= 0; i--)
{
if (textCompare[i] == null)
{
textCompare.RemoveAt(i);
}
}
foreach (string item in textInput)
{
matches = textInput.Intersect(textCompare).ToList();
increment++;
progressBar.Value = increment;
}
//A break point placed on the foreach reveals matches is empty.
foreach (object match in matches)
{
streamWriter.WriteLine(match);
}
doneLabel.Text = "Done!";
}
推荐答案
从您注释的描述中可以做到这一点:
From the description in your comment this would do it:
var textOutput = textCompare.Where(s => !string.IsNullOrEmpty(s))
.Intersect(textInput)
.OrderBy(s => s);
File.WriteAllLines("outputfile.txt", textOutput);
请注意,如果主列表"textInput"中没有空字符串(很可能没有),则可以删除.Where()
条件.另外,如果顺序无关紧要,请删除.OrderBy()
,然后结束此操作:
Note that you can remove the .Where()
condition provided you don't have empty strings in your masterlist "textInput" (very likely there aren't). Also, if order doesn't matter remove the .OrderBy()
, you end up with this then:
var textOutput = textCompare.Intersect(textInput);
File.WriteAllLines("outputfile.txt", textOutput);
这篇关于C#比较两个排序列表并输出到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!