使用C#LINQ在解析字符串中需要帮助 我有一个像这样的字符串
11=205129022,453=8,448=CompanyID,447=D,452=63,448=userid,447=D,452=11,448=CompanyName,447=D,452=13,448=W,447=D,452=54,77=O,555=2
我想将此字符串拆分为448=
,然后取一个数组开始获取行“以448开头”获取行452=
中的最后一个字符串
我正在尝试使用LINQ获取最终输出的逻辑,但它不起作用。
var parties = rptstr.Split(new string[] { "453=" }, StringSplitOptions.None).Select(p => p.Split(new string[] {"448="},StringSplitOptions.None);
var str448 = (from lnprty in parties
where lnprty.ToString().StartsWith("448=")
//let tmp = line1.ToString()
select new PartyRoleModel()
{
companyid == lnprty.Where(s => s.EndsWith("452=63,")).Select(s => s.Substring(s.IndexOf('=') + 1)).FirstOrDefault(),
userid == lnprty.Where(s => s.EndsWith("452=11,")).Select(s => s.Substring(s.IndexOf('=') + 1)).FirstOrDefault()
companyname == lnprty.Where(s => s.EndsWith("452=13,")).Select(s => s.Substring(s.IndexOf('=') + 1)).FirstOrDefault()
PhyFlag == lnprty.Where(s => s.EndsWith("452=54,")).Select(s => s.Substring(s.IndexOf('=') + 1)).FirstOrDefault()
})
.ToList();
我可以按448
拆分行,但448
行没有448=
,因为它已经拆分,我还需要在行中拆分字符串,以便我可以识别该行。
PLS。记住最后一行在结尾(448=W,447=D,452=54,77=O,555=2)
附带其他字符串。
我应该得到最终输出,如452 = 63获得companyid(447 =),452 = 11获取用户ID,452 = 13得到公司名称
提前谢谢。
答案 0 :(得分:0)
请尝试以下操作:
const string FILENAME = @"c:\temp\test.txt";
static void Main(string[] args)
{
Dictionary<int, Dictionary<string, int>> dict = new Dictionary<int, Dictionary<string, int>>();
StreamReader reader = new StreamReader(FILENAME);
string input = "";
while ((input = reader.ReadLine()) != null)
{
//string input = "11=205129022,453=8,448=CompanyID,447=D,452=63,448=userid,447=D,452=11,448=CompanyName,447=D,452=13,448=W,447=D,452=54,77=O,555=2";
List<string> strArray = input.Split(new char[] { ',' }).ToList();
//or dictionary
Dictionary<string, int> rowDict = strArray.Select(x => x.Split(new char[] { '=' })).GroupBy(x => x.Last(), y => int.Parse(y.First())).ToDictionary(x => x.Key, y => y.FirstOrDefault());
int id = rowDict["CompanyID"];
dict.Add(id, rowDict);
}
}