Reputation: 331
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. Default SDP information comes from a device in this form:
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
[email protected] (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 (e.g. with a space before)). 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.
Upvotes: 0
Views: 1342
Reputation: 236218
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):
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
Upvotes: 3
Reputation: 1062780
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:
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
}
}
}
Upvotes: 1