Get the comma separated list from an array - arrays

I have a function which has a return type of IList<Product>
class Product
{
int Id,
string ProductClass,
string ProductName
}
I have to make a comma separated string of ProductName. I am trying below code but it is not giving me correct result
Array arrayofProduct = MyFunction().ToArray();
string productNames = string.Join(",", arrayofProduct);
I think it is because arrayofProduct has 3 columns and I have to pass only 1 (i.e. ProductName) to get the comma separated list.

Use Linq to Select the ProductName into a collection and then use that to construct the desired comma separated string
var names = MyFunction().Select(p => p.ProductName);
string productNames = string.Join(",", names);

Or apart from the above answer you can directly query your array of product and get the result.
string productNames = string.Join(",", arrayofProduct.Select(x => x.ProductName);

Related

How to properly trim string

I am trying to separate an entered name into 2 strings.
Each name is entered in the convention of lastName, firstName
or Ex: Smith, John
I would like to separate the name into a lastName and firstName variable by trimming the string before and after the comma and space.
I have tried
Dim nameSeparator() As Char = {",", " "}
Dim lastName = txtEditName.Text.TrimEnd(nameSeparator)
Dim firstName = txtEditName.Text.TrimStart(nameSeparator)
But after running this, lastName and firstName both equal the full string from txtEditName.Text
If you want to "split" a string in two substrings using a certain separator then you should use the proper method: string.Split
Only after the splitting you can remove unneeded characters at begin or end of a string using the string.Trim method
Dim input() as String = txtEditName.Text.Split(",")
Dim lastName = input(0).Trim()
Dim firstName = input(1).Trim()
Of course this example assumes that you have exactly the input described in your question. If you want to use this approach in a real application then you should check if the result from the splitting produces exactly two substring before trying to access the substrings

How to add formatted String into List or Array?

I have an incoming socket data as shown below;
Example-1:
1#.#4#.#B#.#175.52#.#USD#.#Currency
Example-2:
2#.#4#.#MyName#.#MySurname#.#MyCity#.#MyCountry#.#YourName#.#YourSurname#.#YourCity#.#YourCountry
Explanation for Example-1:
Separator: #.#
Column_count: 4
Rows_count: 1
Col1 Col2 Col3 Col4
Row-1: B 175.52 USD Currency
Explanation for Example-2:
Separator: #.#
Column_count: 4
Rows_count: 2
Col1 Col2 Col3 Col4
Row-1: MyName MySurname MyCity MyCountry
Row-2: YourName. YourSurname YourCity YourCountry
In dart (or flutter) how can I add this into List or Array? What is the best practice?
How can I iterate incoming string use split function and add some array?
Update-1:
I know how to use split function. My problem is that I need to add the string in table, array or map, so I can save it to device and use it later. How can achieve this? I need to use the function in Fluter.
main() {
String mText = "1#.#4#.#B#.#175.52#.#USD#.#Currency";
List<String> mData = mText.split("#.#");
print(mData.toString());
// The List: [1, 4, B, 175.52, USD, Currency]
}
Any help please?
Would this do the job:
List<List<String>> makeTable(String text) {
var entries = text.split("#.#");
if (entries.length < 2) {
throw ArgumentError.value(text, "text", "Invalid format");
}
int row = int.parse(entries[0]);
int col = int.parse(entries[1]);
if (entries.length != 2 + row * col) {
throw ArgumentError.value(text, "text", "Invalid format");
}
return List.generate(row, (i) =>
entries.sublist(2 + i * col, 2 + (i + 1) * col));
}
This parses the first two entries as integers to find the expected dimensions, then creates a list-of-lists (of strings) containing the remaining entries.
Most probably you need to use intl package to handle string manipulation . "This package provides internationalization and localization facilities, including message translation, plurals and genders, date/number formatting and parsing, and bidirectional text."
About your second question - I would create class Person with name, surname, city, country String fields and then have List to hold my data.

Add Single quotes where string contains comma in AngularJS

I have a string which contains values like
var string = A,B,C
Here I want to add single quote for each comma value, expected result should be as below
output = 'A','B','C'
My angular code is
var data = {
output : this.string.split("\',"),
}
which is giving result as
["A,B,C"]
Could anyone please help on this how can I get desired output.
I am understanding your code as
var string = "A,B,C"; // because string should be in this format.
and you just need to replace "\'," from your split function to "," which will give you an array like this
var out = string.split(",");
console.log(out);
[ 'A', 'B', 'C' ] // this is the output.
as split function searches for the given expression and split the string into array.
but if you just want to modify the string without making it in array then you can use the below trick
var out = "'" + string.replace(/,/g, "','") + "'";
console.log(out);
'A','B','C' // result as u mentioned and this is of string type.

User Profile Privacy screen with comma separated String

I have a listView with many fields and CheckBox next to each field. Screen similar to a FaceBook Profile screen with Privacy setting to each field. So friends can not see those fields if marked as Private.
On selection of CheckBox, i have to create a comma separated String.
Example,
FirstName Text ---> isFirstNamePrivate boolean
LastName Text ---> isLastNamePrivate boolean
...
I have to create a
String str = "FirstName,LastName"
if both are marked as Private.
If only isFirstNamePrivate is true then
String str = "FirstName"
Also if i receive a comma separated String from Service, with that i have to make those Boolean array.
Given::
String[] fieldNamesArray = "field1","field2","field3","field4","field5"};
Boolean[] isfieldPrivate = {true,false,true,false,true};
// fieldNamesArray.length will be equal to isfieldPrivate.length
Need to create below commaSeparatedStr from above given arrays.
//
String commaSeparatedStr = "field1,field3,field5";
Question is:
1) What is the optimized way to create a comma separated String.
2) What is the optimized way to create the Boolean array from the commaSeparatedString avoiding for loop on commaSeparatedStr .contains(str[n])
Given::
String[] fieldNamesArray = "field1","field2","field3","field4","field5"};
String commaSeparatedStr = "field1,field3,field5";
Need to create below Boolean array with commaSeparatedStr from above 2 arrays.
Boolean[] isfieldPrivate = {true,false,true,false,true};
// fieldNamesArray.length will be equal to isfieldPrivate.length
//
Where is the question part here?
If you are asking for a suggestion:
If there are 5 fields and first 3 are selected, make your string like
{1,1,1,0,0}
and pass it to your webservice. This would lighten the data package size.

Join an array of strings in Apex

Using Apex, I want to split a string and then rejoin it with the 'AND' operator as the separator.
I split the string successfully but having an issue in rejoining it.
String [] ideaSearchText = searchText.Split(' ');
// How to rejoin the array of strings with 'AND'?
How can I do this?
You can do this as of v26 (Winter 13) by passing your String[] to String.join().
String input = 'valueOne valueTwo valueThree';
String[] values = input.split(' ');
String result = String.join( values, ' AND ' );
Anonymous Apex output calling System.debug(result):
21:02:32.039 (39470000)|EXECUTION_STARTED
21:02:32.039 (39485000)|CODE_UNIT_STARTED|[EXTERNAL]|execute_anonymous_apex
21:02:32.040 (40123000)|SYSTEM_CONSTRUCTOR_ENTRY|[3]|<init>()
21:02:32.040 (40157000)|SYSTEM_CONSTRUCTOR_EXIT|[3]|<init>()
21:02:32.040 (40580000)|USER_DEBUG|[5]|DEBUG|valueOne AND valueTwo AND valueThree
Note if the string object is too large you will get the exception Regex too complicated. In this case you can do something like the following:
Blob blobValue = (Blob)record.get(blobField);
// Truncate string then split on newline, limiting to 11 entries
List<String> preview = blobValue.toString().substring(0,1000).split('\n', 11);
// Remove the last entry, because The list’s last entry contains all
// input beyond the last matched delimiter.
preview.remove(preview.size()-1);
// In my use-case, I needed to return a string, and String.join() works
// as the reverse of split()
return String.join(preview, '\n');

Resources