【C#】从固定格式字符串获取对象(字符串数据转List数据)

核心代码: 

/// <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"));

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

willgon123

谢谢打赏,我将再接再厉!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值