none
LINQ C# - How to split and get value based on my count RRS feed

  • Question

  • Hi,

    How to split and get value based on my count.

    For example,

    I have inputcount = 2
    MyString = "ABC_21-NIM-3547-789_23-278";

    i want to get the final string is "ABC_21-NIM". because my input is "2". so i want to split("-") and get the values.

    so final output after   splitting
     ABC_21-NIM ( here ABC_21 is first string and NIM is second string)

    how to form the values using LINQ C#.?
    Tuesday, December 12, 2017 11:37 AM

Answers

  • Try one more form of Split:

    int inputcount = 2;
    string MyString = "ABC_21-NIM-3547-789_23-278";
     
    string final_output = string.Join( "-", MyString.Split( new[] { '-' }, inputcount + 1 ).Take( inputcount ) );

    • Marked as answer by Gani tpt Wednesday, December 13, 2017 6:06 AM
    Tuesday, December 12, 2017 8:16 PM

All replies

  • You can split and then just select the items and then project only the items specified in the inputcount,it would look something like following:

    int inputcount = 2
    string MyString = "ABC_21-NIM-3547-789_23-278";
    var seperator = '-'; // separator to be used
    var temp = MyString.Split(new char[]{seperator},StringSplitOptions.RemoveEmptyEntries)
                       .Take(inputcount);
    
    var itemsToShow = String.Join('-',temp);
    // ABC_21-NIM

    Hope it helps!

    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

    Tuesday, December 12, 2017 12:17 PM
  • Just another way:
    int inputcount = 2;
    string MyString = "ABC_21-NIM-3547-789_23-278";
    var result = MyString.Split(new char[] { '-' }).TakeWhile((x, index) => index < inputcount);
    Console.WriteLine($"Result: {string.Join("-", result)}");
    
    wizend
    Tuesday, December 12, 2017 12:29 PM
  • Ooops, I just realized my idea isn't exactly very different from yours. But you were faster!

    wizend

    Tuesday, December 12, 2017 12:32 PM
  • Try one more form of Split:

    int inputcount = 2;
    string MyString = "ABC_21-NIM-3547-789_23-278";
     
    string final_output = string.Join( "-", MyString.Split( new[] { '-' }, inputcount + 1 ).Take( inputcount ) );

    • Marked as answer by Gani tpt Wednesday, December 13, 2017 6:06 AM
    Tuesday, December 12, 2017 8:16 PM
  • short and sweet...Thank You. it's working...
    Wednesday, December 13, 2017 6:06 AM