2013-06-04 25 views
3

我有一個列表。StartsWith和List的使用情況列表<string>?

這是可能的成員(x123,y123,z123,a123,b123,c123).//123是example 這個「mylist」可能包含一個以x開頭的成員,或者不可以。這對y,z,a,b,c也是一樣的。

If contains a member starts with x: 
//Formula Contains X 

If Not Contains a member starts with x: 
//Formula Not Contains X 

//same as all of x,y,z,a,b,c. But unlike a foreach, I must place the formulas at checking time, not after. 

我該怎麼做?

+0

你使用LINQ? –

+0

這不會是一個問題,重要的是工作,我可以使用。 – ithnegique

+0

好的。我發佈了一個包含答案並且不包含 –

回答

3

Chec KS有任何項目在列表中以 'X' 開頭:

bool result = mylist.Any(o => o.StartsWith("x")) 

檢查,如果沒有項目與 'X' 的名單開始:

bool result = !mylist.Any(o => o.StartsWith("x")); 
+1

只需定義想要的內容,謝謝。 – ithnegique

2
List<string> formula = new List<string> { "x123", "y123" }; 
string variable = "x"; 
bool containsVariable = formula.Any(s => s.StartsWith(variable)); 
+0

感謝您的解決方案。 – ithnegique

1
public void Process(List<string> list, string key) 
{ 
    if (list.Any(i => i.StartsWith(key))) 
    { 
     //Formula Contains key 
    } 
    else 
    { 
     //Formula Not Contains key 
    } 
} 

,那麼你可以調用

List<string> list = new List<string> { "x123", "y123", "z123", "a123", "b123", "c123"}; 
Process(list, "x"); 
Process(list, "a"); 
5

您可以使用.Any from Linq

bool result = mylist.Any(o => o.StartsWith("x")); 

這會遍歷名單上,並告訴你,如果有啓動至少一個元素帶「x」

+0

在這個解決方案中,我必須放置myList嗎? – ithnegique