简体   繁体   中英

How to convert array of Integers into comma separated string

This is my integer array with Ids

GoalIds{int[7]}
    [0]: 31935
    [1]: 31940
    [2]: 31976
    [3]: 31993
    [4]: 31994
    [5]: 31995
    [6]: 31990

I am getting the above array from this code

Array GoalIds = FilteredEmpGoals.Select(x => x.GoalId).Distinct().ToArray();

I am trying to convert it to comma separated string like

31935, 31940, 31976, 31993, 31994, 31995, 31990

To achieve this I tried

var result = string.Join(",", GoalIds);

but its's giving me "System.Int32[]" in result.

Please let me update where I make a mistake here.

Ref: I looked at here and the example is working fine from there.

UPDATE

REF: As @paqogomez suggested

I was trying to store the values in a Array but may be it was not handling the values correctly. Now I did change the code for making the array as below

int[] GoalIds = FilteredEmpGoals.Select(x => x.GoalId).Distinct().ToArray();

Now it's working fine for me.

In declaring GoalIds as an Array type, you are not getting an iterator to be able to run in String.Join .

Try:

int[] GoalIds = FilteredEmpGoals.Select(x => x.GoalId).Distinct().ToArray();
var result = string.Join(",", GoalIds);

As @JeppeStigNielsen notes in the comments, this is also valid and eliminates the ToArray call:

var GoalIds = FilteredEmpGoals.Select(x => x.GoalId).Distinct();

I have run this code in c# and its work fine dont know what is your problem

int[] GoalIds = new int[7] { 31935,31940, 31976,31993, 31994, 31995, 31990};
var a = string.Join(",", GoalIds);
Console.WriteLine(a);
Console.ReadLine();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM