如何检查项目是否后跟列表中的其他项目? C#

时间:2016-01-25 16:48:39

标签: c# list

我有这些名字:

Sean
Winnie
Brian Amy
Samir
Joe Bethany
Bruno Anna Matthew Lucas
Gabriel Martha Philip
Andre
Danielle
Leo Cinthia
Paula
Mary Jane
Anderson
Priscilla
Regis Julianna Arthur
Mark Marina
Alex Andrea

练习说,名字由一行中的空格隔开,不能互赠礼物。就像狮子座不能给Cinthia送礼物一样,Joe也不能给Bethany等等。

所以我正在寻找一个可以用来检查的代码,如果我有一个列表并且行被导入到该列表中,那么我想检查是否有某个字符串(比如Leo后跟Cinthia)然后是空间,然后这两个人不能互赠礼物。

到目前为止,我在这里:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace SecretSanta
{
    class Program
    {
        static void Main(string[] args)
        {
            StreamReader File = new StreamReader("SSfile.txt");
            List<string> Names = new List<string>();
            string line = File.ReadLine();

            while (line != null)
            {
                Console.WriteLine(line);
                line = File.ReadLine();
                Names.Add(line);
            }

            Console.ReadKey();    
        }
    }
}

2 个答案:

答案 0 :(得分:1)

 class Program
    {
        static Dictionary<string, List<string>> Names = new Dictionary<string, List<string>>();
        static void Main(string[] args)
        {
            StreamReader File = new StreamReader("SSfile.txt");
            string line = File.ReadLine();
            while (line != null)
            {
                Console.WriteLine(line);
                line = File.ReadLine();
                var names = line.Split(" ", StringSplitOptions.RemoveEmptyEntries)
                Names.Add(names[0], names.Skip(1).ToList());
            }
            Console.ReadKey();
        }

        static bool canGive(giver, givee)
        {
           return Names[giver].Any(item => item == givee);
        }
    }

答案 1 :(得分:-2)

问题是,在理解你的问题时,它不会以这种方式工作。

你有一个列表 {&#39; Sean&#39;,&#39; Winnie&#39;,...&#39; Joe&#39;,Bethany&#39;} 因此,如果你检查乔是否跟随伯大尼,然后不允许他给贝瑟尼赠送礼物,你也会禁止肖恩给温妮送礼物...... 我认为您需要多个列表才能实现此功能。 您可以使用包含列表的列表,其中包含一行中的人员 例如 {{&#39; Sean&#39;},{&#39; Winnie&#39;},...,{&#39; Joe&#39;,Bethany&#39;}}

希望我能正确理解你的问题。