tags:

views:

89

answers:

2

I have a database column, delimited by colons, describing a category hierarchy like so:

ID | Category

100 | Domestic:Trees:Fruit:Apples

I would like to extract only the third segment of the hierarchy "Fruit" from the text. How can I use Linq Regex or Linq Filtering to extract just that segment? Is it a good idea to extract information this way for every time a user selects a category?

+1  A: 

Try the String.Split(Char[]) method:

Returns a string array that contains the substrings in this instance that are delimited by elements of a specified Unicode character array.

Basically you can split the original string up based on a delimiter that you specify. This method returns a String[]. Here is a small example of how to use it:

using System;

class Program
{
    static void Main()
    {
     String s = "Domestic:Trees:Fruit:Apples";
     String[] parts = s.Split(':');
     Console.WriteLine(parts[2]);
    }
}
Andrew Hare
+1  A: 

Your question makes it sound like you want a linq answer only - so if you wanted to use linq, you could do this...

string s = "Domestic:Trees:Fruit:Apples".Split(':')
           .Select((item, index) => new {item, index})
           .Where(i => i.index == 2)
           .Select(i => i.item);

Doing it in linq vs just splitting the string and taking the one you need isn't going to make your code any easier to read - so you may want to just consider going with just a straight split as Andrew suggested.

Scott Ivey