从技术上讲,你可以Split几次次:
using System.Linq;
...
string source =
@"BR=PALET90|KS=90|IS=1
BR=PALET60|KS=60|IS=1
BR=EUROPALET|KS=55|IS=1
BR=EUROPALET66|KS=66|IS=1
BR=PALET|KS=75|IS=1";
...
var myList = source
.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
.Select(line => line
.Split('|')
.Select(item => item.Split('='))
.ToDictionary(item => item[0].Trim(), item => item[1]))
.Select(dict => new BIRIM() {
BR = dict["BR"],
KS = int.Parse(dict["KS"]),
IS = int.Parse(dict["IS"])
})
.ToList();
不过,我建议在BIRIM 类中实现TryParse 方法,必要时让这个类自行解析:
using System.Text.RegularExpressions;
...
public class BIRIM {
...
public static bool TryParse(string source, out BIRIM result) {
result = null;
if (string.IsNullOrWhiteSpace(source))
return false;
string br = Regex.Match(source, @"BR\s*=\s*(\w+)").Groups[1].Value;
string KS = Regex.Match(source, @"KS\s*=\s*([0-9]+)").Groups[1].Value;
string IS = Regex.Match(source, @"IS\s*=\s*([0-9]+)").Groups[1].Value;
if (!string.IsNullOrEmpty(br) &&
int.TryParse(KS, out int aks) &&
int.TryParse(IS, out int ais)) {
result = new BIRIM() {
BR = br,
KS = aks,
IS = ais,
};
return true;
}
return false;
}
}
然后就可以实现加载了
var myList = source
.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
.Select(line => BIRIM.TryParse(line, out var value) ? value : null)
.Where(value => value != null)
.ToList();