2012-08-31 45 views
5

我有一個包含字符串的對象數組。從對象數組中加入唯一字符串

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

我想從數組的獨特元素的字符串,,加入也需要檢查,如果字符串isNullOrWhiteSpace;

PIZZA HUT, ISLAMABAD, PAKISTAN. 

目前我正在做以下工作。但是你可以看到它需要在if語句中進行很多檢查。我在想,如果有使用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一種更好的方式包含PIZZA HUT, ISLAMABAD, PAKISTAN, PAKISTAN

+1

我是這麼希望儘量減少 –

回答

10

您可以使用string.Join()方法從你的對象數組中獲得不同的數組元素。

試試這個:

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

那是什麼我正在尋找,讓我試試 –

+2

+1唯一的答案(迄今爲止),包括'IsNullOrWhiteSpace'檢查。 – Laoujin

+1

thx it worked great –

4

是的,你可以使用LINQ:

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

我還需要檢查的空白或空字符串 –

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

我還需要檢查的空白或空字符串 –

0
String.Join(",", values.Distinct().Where(s=>!s.ISNullOrWhiteSpace())) 
相關問題