views:

97

answers:

4

In C#

var parameters =
    from line in parameterTextBox.Lines
    select new {name = line.Split(' ').First(), value = line.Split(' ').Skip(1)};

Is there a way to do this without having to split twice?

+11  A: 

you can store the split in a let clause

var parameters =
    from line in parameterTextBox.Lines
    let split = line.Split(' ')
    select new {name = split.First(), value = split.Skip(1)};
Matt Greer
+1 First correct answer
Ruben Bartelink
A: 

Sure.

var parameters = from line in parameterTextBox.Lines
                 let words = line.Split(' ')
                 select new { name = words.First(), words.skip(1) };
SolutionYogi
-1: Dup of stackoverflow.com/questions/3389963 If one is beaten to the punch and your answer isnt different or better (including you improving your answer to distance it), it should be deleted. Two more downvotes needed and yopu cna get yourself a peer pressure badge.
Ruben Bartelink
This is nonsense. I saw a question and I answered it. I don't care if someone came up with same answers, I am not going to keep following all the other answers in the threads. And where does the SO guidelines say that I should delete my answer if I have been 'beaten to the punch'?
SolutionYogi
A: 

You might try this:

private Dictionary<string, string>getParameters(string[] lines)
{
    Dictionary<string, string> results = new Dictionary<string, string>
    foreach(string line in lines)
    {
        string pName = line.Substring(0, line.IndexOf(' ');
        string pVal = line.Subsgring(line.IndexOf(' ') + 1);
        results.Add(pName, pVal);
    }
    return results;
}
AllenG
+1  A: 
string Str= "one all of the rest";
Match m = Regex.match(Str,"(\w*) (\w.*)");
string wordone = m.Groups[1];
string wordtwo = m.Groups[2];
rerun
This would be a better approach, since not only a whitespace can separate a word.
Pierre-Alain Vigeant
I'd prefer not to use Regex. The LINQ way is clearer.
CookieOfFortune
I would say linq is a different way of doing programming I use linq often but I never think that it looks clean. Though quite effective. I have been using regex for years and is almost always my choice for text parsing
rerun