Convert string to model

旧街凉风 提交于 2019-12-20 07:39:48

问题


Let's say I have this object:

public struct Line
{
    public string Name { get; set; }
    public int Value { get; set; }
    public string Alias { get; set; }
}

And I have a file with lines following this syntax:

garbagedata|moregarbagedata|Name|garbagedata3|Value|garbagedatamaximums|Alias\n

Note that moregarbagedata[x] may or may not exist. A Regex is needed to extract the group-values.

What is easiest and most efficient way to turn this file's lines into a collection of Line objects? Order of this collection does not matter.


回答1:


In my opinion, there are a couple of questions that needs to be asked here.

  1. Can you change the file format?
  2. Is there no way, you can specify a separate delimiter for key/value pairs? {value:garbage,alias:someotherGarbage},{value:secondGarbage....}
  3. Are the lines (Environment.NewLine) the only way packets are separated?

If the answer to 1 is true, then you can use XmlSerializer and Serialize and Deserialize your objects to and fro.

If the answer for 2 is true, then you could look at parsing the file manually using regex or reading line by line and just looking for Value: and then assume that the next item is the value of "Value"

if the answer for 3 is true, Possibly the same answer as 2.

I hope this helps.



来源:https://stackoverflow.com/questions/3911732/convert-string-to-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!