Вы находитесь на странице: 1из 6

Задание

Необходимо создать классы для представления объектов, описанных


ниже. Подразумевается использование в этих классах вложенных коллекций
объектов. Для вложенных коллекций использовать стандартные или
самостоятельные типы-коллекции (список, словарь, множество и т.п.).
Обеспечить реализацию интерфейса IEnumerable<T> для коллекций.
Тест содержит коллекцию вопросов, а вопрос - варианты ответов.
Решение:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace IPR1
{
class Program
{
static void Main(string[] args)
{
var question1 = new Question { Name = "Question1" };
question1.Answers = new List<Answer> {
new Answer {
Name = "Answer1",
isCorrect = false
},
new Answer {
Name = "Answer2",
isCorrect = false
},
new Answer {
Name = "Answer3",
isCorrect = true
},
new Answer {
Name = "Answer4",
isCorrect = false
},
};

var question2 = new Question { Name = "Question2" };


question2.Answers = new List<Answer> {
new Answer {
Name = "Answer1",
isCorrect = true
},
new Answer {
Name = "Answer2",
isCorrect = false
},
new Answer {
Name = "Answer3",
isCorrect = false,
},
new Answer {
Name = "Answer4",
isCorrect = false
},
};
var test = new Test
{
Questions = new List<Question> { question1, question2 }
};

foreach (var question in test)


{
Console.WriteLine(question.Name + ":");
foreach (var answer in question)
{
Console.WriteLine(answer.Name);
Console.WriteLine(answer.isCorrect);
}
}

Console.WriteLine();
Console.WriteLine();

var correctAnswers = test.SelectMany(x => x.Answers.Where(y => y.isCorrect));

var correctAndIncorrectAnswers = test.SelectMany(x => x).GroupBy(x =>


x.isCorrect);

var lookupAnswers = test.SelectMany(x => x).ToLookup(y => y.isCorrect);

var count = test.Count(x => x.Answers.Count == 4);

SaveToTextFile(test);
var s = ReadFromTextFile();

SaveToBinaryFile(test);
var s1 = ReadFromBinaryFile();

Console.ReadKey();
}

static void SaveToTextFile(Test test)


{
try
{
using (var sw = new StreamWriter("test1.txt"))
{
foreach (var question in test)
{
sw.WriteLine($"Question {question.Name}{Environment.NewLine}");
foreach (var answer in question)
{
sw.WriteLine($"Answer {answer.Name}
{answer.isCorrect}{Environment.NewLine}");
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
throw;
}
}

static Test ReadFromTextFile()


{
Test test = new Test
{
Questions = new List<Question>()
};

try
{
using (var sr = new StreamReader("test1.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (line.StartsWith("Question "))
{
var lines = line.Split();
test.Questions.Add(new Question
{
Name = lines[1],
Answers = new List<Answer>()
});
}

if (line.StartsWith("Answer "))
{
var lines = line.Split();

var count = test.Questions.Count;


var last = test.Questions[count - 1];

last.Answers.Add(new Answer { Name = lines[1], isCorrect =


Convert.ToBoolean(lines[2]) });
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
throw;
}

return test;
}

static void SaveToBinaryFile(Test test)


{
try
{
using (var sw = new BinaryWriter(File.Open("test2.b",
FileMode.OpenOrCreate)))
{
foreach (var question in test)
{
sw.Write("Q" + question.Name);

foreach (var answer in question)


{
sw.Write("N" + answer.Name);
sw.Write(answer.isCorrect);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
throw;
}
}

static Test ReadFromBinaryFile()


{
Test test = new Test
{
Questions = new List<Question>()
};

try
{
using (var br = new BinaryReader(File.Open("test2.b",
FileMode.OpenOrCreate)))
{
while (br.PeekChar() > 0)
{
var name = br.ReadString();

if (name[0] == 'Q')
{
name = name.Remove(0, 1);

test.Questions.Add(new Question
{
Name = name,
Answers = new List<Answer>()
});
}

if (name[0] == 'N')
{
name = name.Remove(0, 1);

var count = test.Questions.Count;


var last = test.Questions[count - 1];

var isCorrect = br.ReadBoolean();

last.Answers.Add(new Answer { Name = name, isCorrect =


isCorrect });
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
throw;
}

return test;
}
}

class Question : IEnumerable<Answer>


{
public string Name { get; set; }
public List<Answer> Answers { get; set; }
public IEnumerator<Answer> GetEnumerator() => Answers.GetEnumerator();

IEnumerator IEnumerable.GetEnumerator() => Answers.GetEnumerator();


}

class Test : IEnumerable<Question>


{
private class TestEnumerator : IEnumerator<Question>
{
private readonly Question[] questions;
private int position = -1;

public TestEnumerator(Question[] questions)


{
this.questions = questions;
Array.Copy(this.questions, questions, this.questions.Length);
}

public Question Current { get => questions[position]; }

object IEnumerator.Current { get => questions[position]; }

public bool MoveNext()


{
if (position < questions.Length - 1)
{
position++;
return true;
}

return false;
}

public void Reset()


{
position = -1;
}

public void Dispose()


{
//nothing
}
}

public List<Question> Questions;

public IEnumerator<Question> GetEnumerator()


{
return new TestEnumerator(Questions.ToArray());
}

IEnumerator IEnumerable.GetEnumerator()
{
return new TestEnumerator(Questions.ToArray());
}
}
}

Вам также может понравиться