1

I have some code as below:

char[] separator = { ',' };

String[] idList = m_idsFromRequest.Split(separator);  //m_idsFromRequest="1,2....";
List<string> distinctIdList = idList.Distinct().ToList();
m_distinctIdList = distinctIdList.ToArray();
m_idsFromRequest = string.Join(" ", distinctIdList);

currently m_idsFromRequest = ["1","2".........."] is as such. I want to make it ["0|1","0|2".........."] like append "0|" in each element . I wanted to know id I could do it without the foreach loop.

4
  • FYI your original code can be reduced to m_idsFromRequest = string.Join(" ", m_idsFromRequest.Split(separator).Distinct()); and you'll avoid creating the unneeded intermediate list and array. Commented May 12, 2021 at 14:08
  • Also if your string has brackets at both ends then something like ["1","1"] would not change as the distinct is being applied to values of ["1" and '"1"] Commented May 12, 2021 at 14:09
  • sure I'll look into that. there is some in-between jugglery done with the intermediate data so I've just put up the overall stuff. besides i ain't allowed to touch much code as per my seniors. Commented May 12, 2021 at 14:11
  • 1
    Note the answers below are assuming you're starting with a string like 1,2,3 and not a string like ["1","2","3"] and would not work with the later values so the exact format of the initial string is important here. Commented May 12, 2021 at 14:13

2 Answers 2

4
char[] separator = { ',' };
string m_idsFromRequest = "1,2,3,4,5,6";
String[] idList = m_idsFromRequest.Split(separator);  //m_idsFromRequest="1,2....";
List<string> distinctIdList = idList.Distinct().Select(t => "0|" + t).ToList();
m_idsFromRequest = string.Join(",", distinctIdList);

Just added the .Select() after .Distinct(). Inside the .Select you can transform each of the item in the list.

Apart from that i also added "," in your string.Join. Because you want it to be join by comma.

Sign up to request clarification or add additional context in comments.

1 Comment

@Martin i have added the answer
4

You can use Select and String.Join:

var idsPrependedWithZero = m_idsFromRequest.Split(separator)
    .Distinct() // same as in your code
    .Select(id => $"0|{id}");
string result = string.Join(",", idsPrependedWithZero);

2 Comments

You forgot the Distinct
@juharr: where OP mentioned that they must be unique? Edit: I see. Fixed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.