从类中创建一个IEnumerable

时间:2017-09-29 15:57:06

标签: c#

我有两个课程&#34; Word.cs&#34;和#34; TrainerFile.cs&#34;。 TrainerFile包含5个不同List<Word>的集合,Word包含2个字符串Lang1和Lang2。我需要的是TrainerFile中所有单词的List或enum,这样我就可以随机列出所述TrainerFile的单词。我不知道如何访问所有单词。这是两个班级:

public class Word
{
    public string Lang1 { get; set; }
    public string Lang2 { get; set; }

    public Word()
    {
        this.Lang1 = "";
        this.Lang2 = "";
    }

    public Word(string lang1, string lang2)
    {
        this.Lang1 = lang1;
        this.Lang2 = lang2;
    }
}

public class TrainerFile
{
    public List<Word> FolderInitial { get; set; }
    public List<Word> Folder1 { get; set; }
    public List<Word> Folder2 { get; set; }
    public List<Word> Folder3 { get; set; }
    public List<Word> FolderFinal { get; set; }

    public TrainerFile()
    {
        this.FolderInitial = new List<Word>();
        this.Folder1 = new List<Word>();
        this.Folder2 = new List<Word>();
        this.Folder3 = new List<Word>();
        this.FolderFinal = new List<Word>();
    }

    public TrainerFile(List<Word> listInitial, List<Word> list1, List<Word> list2, List<Word> list3, List<Word> listFinal)
    {
        this.FolderInitial = listInitial;
        this.Folder1 = list1;
        this.Folder2 = list2;
        this.Folder3 = list3;
        this.FolderFinal = listFinal;
    }
}

2 个答案:

答案 0 :(得分:4)

使用linq&#39; s Concat

var result = FolderInitial.Concat(Folder1)
                          .Concat(Folder2)
                          .Concat(Folder3)
                          .Concat(FolderFinal);
  • 如果您想要一个不同的列表,那么何时不使用Concat Union并覆盖Word类的EqualsGetHashCode方法,以便按类的属性进行比较。
  • 另一种方法是提供IEqualityComparer this overload of Union
  • 而不是覆盖这些方法

此外,由于C#6.0,您可以使用默认构造函数:

public class TrainerFile
{
    public List<Word> FolderInitial { get; set; } = new List<Word>();
    public List<Word> Folder1 { get; set; } = new List<Word>();
    public List<Word> Folder2 { get; set; } = new List<Word>();
    public List<Word> Folder3 { get; set; } = new List<Word>();
    public List<Word> FolderFinal { get; set; } = new List<Word>();
}

答案 1 :(得分:-1)

看起来像Dictionary<string, List<Word>>

的情况
Dictionary<string, List<Word>> trainerFile = new Dictionary<string, List<Word>>();
trainerFile.Add("FolderInitial", new List<Word>());
trainerFile.Add("Folder1", new List<Word>());
trainerFile.Add("Folder2", new List<Word>());
trainerFile.Add("Folder3", new List<Word>());
trainerFile.Add("FolderFinal", new List<Word>());

然后像这样访问:

List<string> initial = trainerFile["FolderInitial"];
trainerFile["Folder2"].Add(new Word());
Word word = trainerFile["Folder2"][0];

要访问每个单词,

IEnumerable<Word> all = trainerFile.Values.SelectMany(i => i);