WPF comparing strings in separate files
I have 2 files one is a CSV file and the second is a text file. My requirement is I 开发者_开发知识库want to check if the strings contained in the CSV file exist in the text file. After I have performed this check I want to add those CSV strings that exist in the text file to an IEnnumerable collection which I will use for binding. E.g if CSV conatins "aa", "bb", "cc" and text file contains "bb", "ee", "ff", "cc", "bb" my collection should contain "bb", "cc", "bb". I have made a start on reading from a CSV file using the code below. Can anyone provide a solution pls? Thanks - Ben
public class VM
{
public VM()
{
Words = LoadWords(filePath);
}
public IEnumerable<string> Words { get; private set; }
string filePath = @"Z:\My Documents\Words.csv";
private static IEnumerable<string> LoadWords(String filePath)
{
List<String> words = new List<String>();
try
{
foreach (String line in File.ReadAllLines(filePath))
{
string[] rows = line.Split(',');
words.AddRange(rows);
}
}
catch (Exception e)
{
System.Windows.MessageBox.Show(e.Message);
}
return words;
}
}
You can do this with LINQ, something like:
var csv = new[] { "aa", "bb", "cc" };
var text = new[] { "bb", "ee", "ff", "cc", "bb" };
IEnumerable<string> collectionToBind = text.Where(t => csv.Contains(t));
精彩评论