[英]Parse string using C# LINQ
Need help in parse string using C# LINQ I have a string like this 在使用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
I would like to split this string on 448=
then take an array start getting line "starts with 448" get the last string in the line which is 452=
I'm trying this logic using LINQ to get the final output but it's not working. 我想在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();
I can split the line by 448
but 448
lines comes without 448=
since it got split, I need split string also in the line so I can identify the line. 我可以将行分割为448
但是448
行不带448=
因为它已经被分割了,所以我也需要在行中分割字符串,以便识别该行。 Pls. 请 remember the last line comes with other strings at end (448=W,447=D,452=54,77=O,555=2)
. 记住最后一行在结尾处带有其他字符串(448=W,447=D,452=54,77=O,555=2)
。 I should get the final output like where 452=63 get companyid(which is in 447=), 452=11 get userid, 452=13 get companyname Thanks in advance. 我应该得到最终输出,例如452 = 63 get companyid(in 447 =),452 = 11 get userid,452 = 13 get companyname谢谢。
Try following : 尝试以下操作:
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.