C# - 使用 CSV/Excel 数据和选择特定数据的简单方法?

标签 c# winforms csv

我目前正在开发一款危险类型游戏,并希望包含一个包含问题的 CSV 文件,因此如果有人打算再次玩该游戏,则会有更多关于该游戏的问题。我正在努力找出一种方法将此 CSV 文件分为某种类别。到目前为止,我对每个点按钮都有两个问题。每当按下按钮时,我希望它从文件中检索问题并在这两个问题之间进行随机化,然后在文本框中显示所选问题。

如果有人对我可以使用的方法提出建议,我愿意倾听!

到目前为止,我已经尝试了 YouTube 上几乎所有的 C# CSV 文件教程,问题是它们都没有按照我想要的方式处理数据,这对我来说很复杂。

我当然会提供您需要的一切来帮助我。 提前谢谢您! :)

最佳答案

编辑 - 2020-04-08 22:57 (UTC+03:00)

请找到下面的工作表格。只需复制/粘贴到 form1.cs

using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using CsvHelper;
using CsvHelper.Configuration;

namespace EksamensprojektTest
{
    public partial class Form1 : Form
    {
        static Values[] allRecords;
        static Random randomNumberGenerator = new Random();

        private string currentCategory = "Danish";
        private int currentPoints = 100;

        public Form1()
        {
            InitializeComponent();
        }

        public sealed class CsvRecordMap : ClassMap<Values>
        {
            public CsvRecordMap()
            {
                Map(m => m.ID);
                Map(m => m.Question);
                Map(m => m.Answer);
                Map(m => m.Points);
                Map(m => m.Category);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            using (var reader = new StreamReader("C:\\Users\\mathi\\OneDrive\\HTX\\3.g\\Programmering\\Eksamensprojekt\\csvfil.csv"))
            {
                using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
                {
                    csv.Configuration.RegisterClassMap<CsvRecordMap>();
                    allRecords = csv.GetRecords<Values>().ToArray();
                }
            }
        }

        public static Values GetRandomQuestion(string category, int points)
        {
            var matchingQuestions = allRecords
                .Where(x => x.Category == category && x.Points == points)
                .ToArray();

            if (matchingQuestions.Length == 0) { return null; }

            // if length is 2, random returns 0 or 1.
            // if length is 3, random returns 0 or 1 or 2, etc.
            int randomChoice = randomNumberGenerator.Next(0, matchingQuestions.Length);
            return matchingQuestions[randomChoice];
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Values pickedRecord = GetRandomQuestion(currentCategory, currentPoints);
            textBox1.Text = pickedRecord.Question;
        }
    }
}

编辑:

可以使用以下方法来获取具有指定类别和分数的随机问题。 allRecords 数组与原始答案相同,并且填充方式相同。这个方法只是一个补充:

请将其放在类(class)级别:

static Random randomNumberGenerator = new Random();

然后是方法:

public static CsvRecord GetRandomQuestion(string category, int points)
{
    var matchingQuestions = allRecords
        .Where(x => x.Category == category && x.Points == points)
        .ToArray();

    if (matchingQuestions.Length == 0) { return null; }

    // if length is 2, random returns 0 or 1.
    // if length is 3, random returns 0 or 1 or 2, etc.
    int randomChoice = randomNumberGenerator.Next(0, matchingQuestions.Length);
    return matchingQuestions[randomChoice];
}

原始帖子

我已经实现了一个完全有效的解决方案,它将所有 csv 文件作为 CsvRecord 类的实例加载到内存中。

我创建的 csv 文件如下所示。请注意,标题(字段名称)很重要。它应该与我们的属性名称匹配。如果没有,我们仍然有解决方法,但我认为它们是相同的。

默认情况下,csv 数据应以逗号分隔。此行为也可以更改。

Id,Category,Points,Question,Answer
1,History,100,Question 1 (History) - 100 Points,Answer 1 (History) - 100 Points
2,History,100,Question 2 (History) - 100 Points,Answer 2 (History) - 100 Points
3,History,200,Question 3 (History) - 200 Points,Answer 3 (History) - 200 Points
4,History,200,Question 4 (History) - 200 Points,Answer 4 (History) - 200 Points
5,History,300,Question 5 (History) - 300 Points,Answer 5 (History) - 300 Points
6,History,300,Question 6 (History) - 300 Points,Answer 6 (History) - 300 Points
7,History,400,Question 7 (History) - 400 Points,Answer 7 (History) - 400 Points
8,History,400,Question 8 (History) - 400 Points,Answer 8 (History) - 400 Points
9,History,500,Question 9 (History) - 500 Points,Answer 9 (History) - 500 Points
10,History,500,Question 10 (History) - 500 Points,Answer 10 (History) - 500 Points
11,Science,100,Question 11 (Science) - 100 Points,Answer 11 (Science) - 100 Points
12,Science,100,Question 12 (Science) - 100 Points,Answer 12 (Science) - 100 Points
13,Science,200,Question 13 (Science) - 200 Points,Answer 13 (Science) - 200 Points
14,Science,200,Question 14 (Science) - 200 Points,Answer 14 (Science) - 200 Points
15,Science,300,Question 15 (Science) - 300 Points,Answer 15 (Science) - 300 Points
16,Science,300,Question 16 (Science) - 300 Points,Answer 16 (Science) - 300 Points
17,Science,400,Question 17 (Science) - 400 Points,Answer 17 (Science) - 400 Points
18,Science,400,Question 18 (Science) - 400 Points,Answer 18 (Science) - 400 Points
19,Science,500,Question 19 (Science) - 500 Points,Answer 19 (Science) - 500 Points
20,Science,500,Question 20 (Science) - 500 Points,Answer 20 (Science) - 500 Points
21,Geography,100,Question 21 (Geography) - 100 Points,Answer 21 (Geography) - 100 Points
22,Geography,100,Question 22 (Geography) - 100 Points,Answer 22 (Geography) - 100 Points
23,Geography,200,Question 23 (Geography) - 200 Points,Answer 23 (Geography) - 200 Points
24,Geography,200,Question 24 (Geography) - 200 Points,Answer 24 (Geography) - 200 Points

然后,下面的类(这是一个完整的控制台应用程序)演示了加载 csv 文件、过滤和选择要提出的问题。

我希望这会有所帮助。我还到处添加了一些注释行来解释事情。

using System;
using System.Globalization;
using System.IO;
using CsvHelper;
using CsvHelper.Configuration;
using System.Linq;

namespace console
{
    public class Program
    {
        public class CsvRecord
        {
            public string Id { get; set; }
            public string Category { get; set; }
            public int Points { get; set; }
            public string Question { get; set; }
            public string Answer { get; set; }
        }

        public sealed class CsvRecordMap : ClassMap<CsvRecord>
        {
            public CsvRecordMap()
            {
                Map(m => m.Id);
                Map(m => m.Category);
                Map(m => m.Points);
                Map(m => m.Question);
                Map(m => m.Answer);
            }
        }

        static CsvRecord[] allRecords;

        static void Main(string[] args)
        {
            // Fill all records into a shared array (allRecords)
            // CSVHelper reads our csv file and creates a CsvRecord
            // instance for each row using our ClassMap implementation
            using (var reader = new StreamReader("data.csv"))
            {
                using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
                {
                    csv.Configuration.RegisterClassMap<CsvRecordMap>();
                    allRecords = csv.GetRecords<CsvRecord>().ToArray();
                }
            }

            Console.WriteLine("Enter a category and points to get a random question");

            Console.Write("Category: "); string category = Console.ReadLine();
            Console.Write("Points: "); int points = int.Parse(Console.ReadLine());

            // using System.LinQ;
            // A simple filter
            CsvRecord[] matchingRecords = allRecords.Where(a => a.Category == category && a.Points == points).ToArray();

            Console.WriteLine("{0} records found", matchingRecords.Length);

            // Randomly select one of the two
            Random random = new Random();
            CsvRecord pickedRecord = matchingRecords[random.Next(matchingRecords.Length)];

            Console.WriteLine("Selected: {0}", pickedRecord.Question);
        }
    }
}

关于C# - 使用 CSV/Excel 数据和选择特定数据的简单方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60929728/

相关文章:

c# - 如何退出所有正在运行的线程?

python - 如何简单地使用 Python API 将文本文件放入 sqlite?

C# 扩展方法未定义

c# - 如何区分测试类中的单元测试和集成测试?

c# - 多次播放后 MediaElement 失败

c# - 属性更改时未更新列表框项目

c# - 限制非数值运算

c# - 始终以基本形式处理 PreviewKeyDown 事件

java - 在数据库中存储特殊字符

python - 从 CSV 创建特定格式的 JSON 文件