繁体   English   中英

使用C#LINQ解析字符串

[英]Parse string using C# LINQ

在使用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=因为它已经被分割了,所以我也需要在行中分割字符串,以便识别该行。 记住最后一行在结尾处带有其他字符串(448=W,447=D,452=54,77=O,555=2) 我应该得到最终输出,例如452 = 63 get companyid(in 447 =),452 = 11 get userid,452 = 13 get companyname谢谢。

尝试以下操作:

        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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM