在c#中打印来自foreach的一行

时间:2014-09-24 14:24:37

标签: c# printing symbols

我正在尝试从列表(matchedSymbols)打印符号(trimmedLine)和值,而是打印每个符号的所有有效符号的所有值。我尝试不使用foreach循环,但随后它会打印搜索到的最后一个符号的值,这是无效的。以下是我目前的方法代码:

public void searchSymbolTable()
    {
        string searchingForFile = "";
        string[] searchFile;

        Console.Write("Enter the name of the search file: ");
        searchingForFile = @"../../" + Console.ReadLine();
        Console.WriteLine("Searching symbol table...");
        Console.WriteLine();

        while (!File.Exists(searchingForFile))
        {
            Console.Write("File not found, try again or enter 1 to exit: ");
            searchingForFile = @"../../" + Console.ReadLine();
            if (searchingForFile == @"../../1")
            {
                Environment.Exit(1);
            }
        }

        searchFile = File.ReadAllLines(searchingForFile);


        matchedSymbols = new List<symbols>();
        var space = ' ';

        foreach (string line in searchFile)
        {
            try
            {
                var trimmedLine = line.Trim();
                var tokens = trimmedLine.Split(space);

                trimmedLine = checkSymbol(tokens[0]);

                matchedSymbols.Add(mySymbols.ToList().Find(symName => symName.ToString() == trimmedLine));


                if (matchedSymbols[matchedSymbols.Count() - 1] == null)
                {
                    throw new Exception(string.Format("ERROR - Symbol {0} not found in symbol table.", trimmedLine));
                }
                else
                {
                   foreach(symbols s in mySymbols)
                   {

                           Console.WriteLine(string.Format("{0,-10} {1}", trimmedLine, s.value));

                   }

                }
            }
            catch (Exception e)
            {

                Console.WriteLine(e.Message);
                if (Console.CursorTop % 20 == 19)
                {
                    Console.Write("Press any key to continue ...");
                    Console.ReadKey();
                }

            }
        }
    }

1 个答案:

答案 0 :(得分:0)

由于你只是在寻找一场比赛,所以你不需要内在的前线......

我已将Find替换为将选择第一个匹配(或返回null)的Linq

var trimmedLine = line.Trim();
var tokens = trimmedLine.Split(space);

trimmedLine = checkSymbol(tokens[0]);

//look for the match, select the first (null if no matches)
var matchedSymbol = mySymbols.FirstOrDefault(symName => symName.ToString() == trimmedLine);

//if null (no match)                
if (matchedSymbol == null)
{
    throw new Exception(string.Format("ERROR - Symbol {0} not found in symbol table.", trimmedLine));
}
else
{
    //print the match
    Console.WriteLine(string.Format("{0,-10} {1}", trimmedLine, matchedSymbol.value));
    //add the match to your collection of matches
    matchedSymbols.Add(matchedSybol);
}