循环列表,匹配列表中的单词调用描述

时间:2013-11-23 13:53:03

标签: c# list loops streamreader

我在构建一个循环时遇到问题,这个循环会将VAR(userSelection)与我的LIST(列表)中的名称ITEMS进行比较。目标是,如果userSelection为MATCHES名称,则getDescription将Console.WriteLine的GetDefinition和显示匹配列表中单词的定义。我的大多数代码都在工作,我已经在这个任务上工作了一个星期。

我非常喜欢新手,请假设我什么都不知道。所有帮助表示赞赏。我认为这将是一个循环,但我现在玩了所有的循环,我迷失了和困惑。我是个新手,请用小词,尽可能详细。非常感谢。谢谢。

我的C#计划:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Threading.Tasks;// Needed for Streaming...
using System.IO;// Needed for Streaming...

namespace a090___StreamReader_DictionarySearch
{
class Program
{
    private const String FILE_NAME = "dictionary.txt";//establish text file instance

    public void Play()
    {
        do
        {
            DisplayTitle();

            List<Listing> items = LoadListings();//create a list of WordDef objects

            Console.Write(string.Join(" | ", items.Select(x => x.GetName()))); //Console.Write("\b \b");// Backspace would also of worked


            DisplayText("\n\nPlease enter a word from the selections about to see it's definition");// Nice use of PROMPT
            String userSelection = Console.ReadLine().ToLower();//Capture input

            //loop through all of the listings, and compare each one to userSelection
            //Then once it equals print definition

            bool found = false;

            foreach (Listing item in items)
            {
                if (userSelection == item.GetName())
                {
                    Console.WriteLine("You selected: " + userSelection +
                                "\nWhich Means: " + item.GetDefinition());
                    found = true;
                    break;
                }
            }

            if (!found)
            { Console.WriteLine("I'm sorry, I don't have a match for that."); }

        } while (PlayAgain());

        Salutation();
    }

    //ToolBox -- my program specific tools
    public List<Listing> LoadListings()//load entries display as list
    {
        StreamReader fileIn = new StreamReader(FILE_NAME);
        List<Listing> entry = new List<Listing>();

        //loop through every line of the file
        while (!fileIn.EndOfStream)
        {
            String line = fileIn.ReadLine();
            String[] pieces = line.Split(':');

            if (pieces.Length < 1) continue;//error handling - set to length of text items

            Listing myListing = new Listing(pieces[0], pieces[1]);
            entry.Add(myListing);
        }
        fileIn.Close(); return entry;
    }




    //MaxBox -- my useful tools
    public void DisplayText(String StringNameIs)
    { Console.WriteLine(StringNameIs); }//Where are we?

    public Boolean PlayAgain()
    {
        Console.Write("\n\nDo you select again? (y)es or (n)o: ");
        String command = Console.ReadLine().ToLower();

        if (command == "y" || command == "yes") return true;
        return false;
    }

    public void Salutation()
    { Console.Clear(); Console.WriteLine("Ti Do - oh - oh Ti Do -- So Do!"); } //The last line from the 'do-re-mi' song from the Sound of Music

    public void DisplayTitle()
    { Console.Clear(); Console.WriteLine(">>>-- A Dictionary of Sounds --<<< \n"); } //Announce Our Program  



    static void Main(string[] args)
    {
        Program DictionaryLookup = new Program();
        DictionaryLookup.Play();
        Console.Read();
    }
}
}

我的班级

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace a090___StreamReader_DictionarySearch
{
class Listing
{
    private String name;
    private String definition;

    public Listing(String name, String definition)
    { this.name = name; 
      this.definition = definition;}

    public String GetName()       {return name;}
    public String GetDefinition() {return definition; }
}
}

我的文字档案

Doe: a deer, a female deer
Ray: a drop of golden sun
Me: a name I call myself
Far: a long, long way to run
Sew: a needle pulling thread
La: a note to follow Sew

茶:果酱和面包的饮料

2 个答案:

答案 0 :(得分:1)

这是未经测试的,但应该可以使用您现有的代码。

假设每个“名字”(doe,ray等)只出现一次(他们这样做),那么你可以使用Linq的“SingleOrDefault”,如果找不到匹配则返回null

var selection = items.SingleOrDefault(x => x.GetName() == userSelection);

if (selection == null)
    Console.WriteLine("I'm sorry, I don't have a match for that.");
else
    Console.WriteLine("You selected: " + userSelection +
                      "\nWhich Means: " + selection.GetDefinition());

要在比较期间忽略大小写,请尝试修改上述内容:

... items.SingleOrDefault(x => String.Compare(x.GetName(), userSelection, true));

您可以在此处更改其他一些内容,但也许这对您的任务无关紧要。例如,我将消除Listing类中的私有变量,并将公共“get”方法更改为属性:

public String Name { get; private set; }
public String Definition { get; private set; }

答案 1 :(得分:1)

替换代码

while (true)
            {
                if (userSelection == name)
                {Console.WriteLine("You selected: " + Listing.userSelection() +
                                "\nWhich Means: " + Listing.items.GetDefinition());}
            }
           else { Console.WriteLine("I'm sorry, I don't have a match for that."); }

用这个

        bool found = false;

        foreach (Listing item in items)
        {
            if (userSelection == item.GetName().ToLower())
            {
                Console.WriteLine("You selected: " + userSelection +
                            "\nWhich Means: " + item.GetDefinition());
                found = true;
                break;
            }
        }


        if (!found)
        { Console.WriteLine("I'm sorry, I don't have a match for that."); }

我使用了foreach声明;使用此语句,您可以迭代集合中的所有项目。

在foreach循环中,我检查元素Name是否与用户输入相等,如果匹配,我设置一个bool变量指示找到的元素。

循环后如果找不到元素则打印消息。

NB显然,这段代码可以用LINQ更简洁地编写。