none
Use Split in a Linq expression RRS feed

  • Question

  • Hello

    I'm attempting to get a substring from a string, and I'm currently using split, then I index into an array.

    wondering how I can do this with a linq expression

                      

                   
    var k = myObject.GetType(); 
    var nameSpace = k.Namespace;
    
    if (nameSpace != null && nameSpace.Contains("Users.Past.Employee.")) 
           {
             var myArray = nameSpace.Split('.');
             var namespacenmae = myArray [3];
           }

    Monday, January 22, 2018 3:50 PM

All replies

  • //Get the whole array
    var namespaces = namespace.Split('.');
    
    //Get the last namespace value
    var namespaces = namespace.Split('.').LastOrDefault();


    Michael Taylor http://www.michaeltaylorp3.net

    Monday, January 22, 2018 4:16 PM
    Moderator
  • You can use LastOrDefault()  if you are looking to get the last item in the delimited string :

    var myArray = nameSpace.Split(new char[]{'.'},StringSplitOptions.RemoveEmptyEntries);
    var namespacenmae = myArray.LastOrDefault();

    or what you are looking for is the 3rd item in the array, then you can use Skip and Take :

    var myArray = nameSpace.Split(new char[]{'.'},StringSplitOptions.RemoveEmptyEntries);
    var namespacenmae = myArray.Skip(2).Take(1).FirstOrDefault();

    Hope it helps!


    [If a post helps to resolve your issue, please click the "Mark as Answer" of that post or click Answered "Vote as helpful" button of that post. By marking a post as Answered or Helpful, you help others find the answer faster. ]


    Blog | LinkedIn | Stack Overflow | Facebook
    profile for Ehsan Sajjad on Stack Exchange, a network of free, community-driven Q&A sites

    Monday, January 22, 2018 7:31 PM