C#将字符串解析为对象

Sha*_*eKm -1 .net c#

对于以下文字:

Item 1:
student-pay
history 320.00
math 500.10 extra

Item 2:
history 220.00
math 200.10
Run Code Online (Sandbox Code Playgroud)

我想将此文本解析为Item类.有没有更有效的方法来做到这一点?

我有以下内容:

            var result = input.Split(
                new[] { "item", "Item" }, 
                StringSplitOptions.RemoveEmptyEntries);

            foreach (string item in result)
            {
                var lineItems = item.Split(
                    new[] { Environment.NewLine }, 
                    StringSplitOptions.RemoveEmptyEntries);

                foreach (var lineItem in lineItems.Skip(1)) // remove ":"
                {
                        // split line again
// check if numeric
                }
            }

public class Course
{
    public bool StudentPay { get; set; }

    public ICollection<CourseItem> JobItems { get; set; }
}

public class CourseItem
{
    public string Name { get; set; }

    public decimal Cost { get; set; }

    public bool Extra { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我想结束 List<Items>

jef*_*eff 5

鉴于数据格式你必须手动编写一个解决方案.

更好的方法是使用json格式.获取Newtonsoft.json.它是一个连接它的衬里和一个衬管到解串器.为File.Write和File.Read添加另一行,然后离开.

使用JsonConvert.Serialize和JsonConvert.Deserialize,将适用于大多数类(与xmlserializer不同).