Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join unique strings from an array of objects

Tags:

c#

linq

c#-4.0

I have an array of objects containing strings.

var values = new object[5];
values[0] = "PIZZA HUT";
values[1] = "ISLAMABAD";
values[2] = "ISLAMABAD";
values[3] = "PAKISTAN";
values[4] = "PAKISTAN";

I want to get a string of unique elements from the array, joined with , also need to check if string isNullOrWhiteSpace;

PIZZA HUT, ISLAMABAD, PAKISTAN. 

Currently I am doing the following. But you can see that it required to much checks in the if statement. I was wondering if there is a better way using LINQ

string featureName = values[0] as string;
string adminboundry4 = values[1] as string;
string adminboundry3 = values[2] as string;
string adminboundry2 = values[3] as string;
string adminboundry1 = values[4] as string;


if (!string.IsNullOrWhiteSpace(adminboundry4) 
   && adminboundry4 != adminboundry1 
   && adminboundry4 != adminboundry2 
   && adminboundry4 != adminboundry3) //want to get rid of these checks
                featureName += "," + adminboundry4;

if (!string.IsNullOrWhiteSpace(adminboundry3)) //Not checking for duplicate here just for this question
                featureName += "," + adminboundry3;

if (!string.IsNullOrWhiteSpace(adminboundry2)) //Not checking for duplicate here just for this question
                featureName += "," + adminboundry2;

if (!string.IsNullOrWhiteSpace(adminboundry1)) //Not checking for duplicate here just for this question
                featureName += "," + adminboundry1;

featureName contains PIZZA HUT, ISLAMABAD, PAKISTAN, PAKISTAN

like image 767
Bilal Hashmi Avatar asked Aug 31 '12 11:08

Bilal Hashmi


People also ask

How to join string in array?

The arr. join() method is used to join the elements of an array into a string. The elements of the string will be separated by a specified separator and its default value is a comma(, ).

How do you join an array of objects?

join() The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.


Video Answer


2 Answers

You can use string.Join() method and get array distinct string elements from your object array.

try this:

var Result = string.Join(",", values.Cast<string>()
                                 .Where(c => !string.IsNullOrWhiteSpace(c))
                                 .Distinct());
like image 111
Habib Avatar answered Oct 16 '22 06:10

Habib


Yes, you can use LINQ:

var featureName = String.Join(
  ",",
  values
    .Cast<String>()
    .Where(s => !String.IsNullOrWhiteSpace(s))
    .Distinct()
);
like image 22
Martin Liversage Avatar answered Oct 16 '22 07:10

Martin Liversage