核心代码:
/// <summary>
/// 字符串数据转List数据
/// </summary>
/// <typeparam name="T">输出类型</typeparam>
/// <param name="content">字符串</param>
/// <param name="splitStr">分割字符</param>
/// <param name="skipLine">跳过开头行数</param>
/// <param name="condition">筛选条件</param>
/// <returns></returns>
public static List<T> GetListFromString<T>(string content, string splitStr = "|", int? skipLine = null, Predicate<string> condition = null)
{
try
{
if (string.IsNullOrWhiteSpace(splitStr))
{
throw new Exception("请给出分割字符");
}
List<T> ResultList = new List<T>();
byte[] array = Encoding.UTF8.GetBytes(content);
using (MemoryStream stream = new MemoryStream(array))
{
using (StreamReader reader = new StreamReader(stream))
{
int line = 0;
string lineStr;
//按行读取内容
while ((lineStr = reader.ReadLine()) != null)
{
line++;
if (skipLine != null && line <= skipLine)
{
continue;
}
//满足条件则继续
if (condition != null && !condition(lineStr))
{
continue;
}
lineStr = lineStr.Replace(splitStr, "|");
string[] fields = lineStr.Split(new char[] { '|' }); //切割字符串
T model = Activator.CreateInstance<T>();
PropertyInfo[] proInfos = model.GetType().GetProperties(); //获取所有属性
for (int i = 0; i < Math.Min(fields.Length, proInfos.Length); i++)
{
proInfos[i].SetValue(model, fields[i]); //对每一个属性赋值
}
ResultList.Add(model);
}
}
}
return ResultList;
}
catch (Exception ex)
{
throw ex;
}
}
代码解释:
主要用于多行格式相同的字符串时,需要转为List数据时,可以使用。
调用方式:
//以"|"做分割,先忽略字符串前面2行,只转换以ABC为开头的字符串
List<Model> list = GetListFromString<Model>(contentStr, "|", 2, (c)=>c.StartsWith("ABC"));