2012-08-31 14 views
5

Ho una matrice di oggetti contenenti stringhe.Unire stringhe univoche da una serie di oggetti

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

voglio ottenere una serie di elementi unici della matrice, uniti con , anche bisogno di controllare se isNullOrWhiteSpace stringa;

PIZZA HUT, ISLAMABAD, PAKISTAN. 

Attualmente sto facendo quanto segue. Ma puoi vedere che ha richiesto molti controlli nella dichiarazione if. Mi chiedevo se c'è un modo migliore utilizzando 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 contiene PIZZA HUT, ISLAMABAD, PAKISTAN, PAKISTAN

+1

questo è quello che voglio minimizzare –

risposta

10

È possibile utilizzare string.Join() metodo e ottieni array di elementi distinti di stringa dal tuo array di oggetti.

provare questo:

var Result = string.Join(",", values.Cast<string>() 
           .Where(c => !string.IsNullOrWhiteSpace(c)) 
           .Distinct()); 
+0

Questo è ciò che Stavo cercando, fammi provare –

+2

+1 L'unica risposta (finora) che includeva il controllo 'IsNullOrWhiteSpace'. – Laoujin

+1

thx ha funzionato benissimo –

4

Sì, è possibile utilizzare LINQ:

var featureName = String.Join(
    ",", 
    values 
    .Cast<String>() 
    .Where(s => !String.IsNullOrWhiteSpace(s)) 
    .Distinct() 
); 
+0

Ho anche bisogno di verificare la presenza di spazi bianchi o stringa nulla –

0
String.Join(",",values.ToList().Distinct(str=>str)) 
+0

Ho anche bisogno di verificare la presenza di spazi bianchi o stringa nulla –

0
String.Join(",", values.Distinct().Where(s=>!s.ISNullOrWhiteSpace())) 
Problemi correlati