简体   繁体   English

使用LINQ查询字符串

[英]Query string using LINQ

For parsing SDP information from an RTSP, currently I use default c# string functions (like loop the string line by line) and foreach/switch methods. 为了从RTSP解析SDP信息,当前我使用默认的c#字符串函数(如逐行循环字符串)和foreach / switch方法。 Default SDP information comes from a device in this form: 默认SDP信息以以下形式来自设备:

v=0
o=mhandley 2890844526 2890842807 IN IP4 126.16.64.4
s=SDP Seminar
i=A Seminar on the session description protocol
u=http://www.cs.ucl.ac.uk/staff/M.Handley/sdp.03.ps
e=mjh@isi.edu (Mark Handley)
c=IN IP4 224.2.17.12/127
t=2873397496 2873404696
a=recvonly
m=audio 3456 RTP/AVP 0
m=video 2232 RTP/AVP 31
m=whiteboard 32416 UDP WB
a=orient:portrait

Im wondering is this string is query-able using LINQ or something instead of foreaching each line, switching the first character and then storing the rest as a value, because this method is very sensitive to malfunction and error (like when 2 attributes/params are on 1 line or the first character isn't accidentally the right one (eg with a space before)). 我想知道是否可以使用LINQ或其他方式查询此字符串,而不是遍历每一行,切换第一个字符,然后将其余字符存储为值,因为此方法对故障和错误非常敏感(例如当两个属性/参数为在第一行上,或者第一个字符不是偶然的正确字符(例如,前面有一个空格)。 Before I begin to cover every damn exception than can occur, I'm wondering if there's a technique to query a string for values/keys using LINQ. 在我开始讨论每一个该死的异常之前,我想知道是否有一种使用LINQ在字符串中查询值/键的技术。

var query = text.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
                .Select(line => line.Split('='))
                .GroupBy(x => x[0], x => x[1])
                .Select(g => new { Key = g.Key, Values = g.ToList() });

This will return entries grouped by key with values as list. 这将返回按键分组的条目,并将值作为列表。

Or this way (if Linq Lookup is OK for you): 或通过这种方式(如果Linq查找对您来说还可以):

var lookup = text.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
                 .Select(line => line.Split('='))
                 .ToLookup(x => x[0], x => x[1]);

Usage: 用法:

foreach (var value in lookup["m"])
    // use value

you undoubtedly can do it with linq, but a simple loop (perhaps using StringReader to get the lines) checking line.Length != 0 then looking and line[0] and line.Substring(1) is probably more appropriate: 您无疑可以使用linq 做到这一点,但是一个简单的循环(可能使用StringReader来获取行)检查line.Length != 0然后看line.Length != 0并与line[0]line.Substring(1)比较合适:

static void Process(string input)
{
    using (var reader = new StringReader(input))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            if(line.Length == 0) continue;

            char first = line[0];
            string rest = line.Substring(1);
            // ... process this line
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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