2015-07-13 41 views
1

對不起,也許noob問題),但我只是想學習新的東西。 我有一個數組,保存與許多領域的對象 - 如何 檢查與選擇是否例如該對象的第一個字段是相同的一些字符串? (本場也是一個字符串,所以沒有類型OPS需要)選擇lambda的用法

+0

「第一「以什麼條件?字母順序的變量名稱? – thumbmunkeys

+0

你能舉一些例子代碼嗎? - 也許調查LINQ擴展方法(首先,任何,地方)...在這方面選擇聽起來像錯誤的方法 – series0ne

+0

'array.Where(a => a.property ==「my string」)。ToList()' –

回答

2

考慮這種情況:

// Some data object 
public class Data { 
    public string Name { get; set; } 
    public int Value { get; set; } 

    public Data(string name, int value) 
    { 
     this.Name = name; 
     this.Value = value; 
    } 
} 

// your array 
Data[] array = new Data[] 
{ 
    new Data("John Smith", 123), 
    new Data("Jane Smith", 456), 
    new Data("Jess Smith", 789), 
    new Data("Josh Smith", 012) 
} 

array.Any(o => o.Name.Contains("Smith")); 
// Returns true if any object's Name property contains "Smith"; otherwise, false. 

array.Where(o => o.Name.StartsWith("J")); 
// Returns an IEnumerable<Data> with all items in the original collection where Name starts with "J" 

array.First(o => o.Name.EndsWith("Smith")); 
// Returns the first Data item where the name ends with "Smith" 

array.SingleOrDefault(o => o.Name == "John Smith"); 
// Returns the single element where the name is "John Smith". 
// If the number of elements where the name is "John Smith" 
// is greater than 1, this will throw an exception. 
// If no elements are found, this` would return null. 
// (SingleOrDefault is intended for selecting unique elements). 

array.Select(o => new { FullName = o.Name, Age = o.Value }); 
// Projects your Data[] into an IEnumerable<{FullName, Value}> 
// where {FullName, Value} is an anonymous type, Name projects to FullName and Value projects to Age. 
+0

謝謝你的完整答案))很高興知道)) – curiousity

+1

@curiousity,不客氣。請注意,這裏有更多的LINQ擴展。您可能想要研究IEnumerable接口,因爲這是LINQ的基礎之一。此外,智能感知文檔將有助於理解每種擴展方法的功能。 – series0ne

1

如果你只是想找到與字段/屬性一定值數組第一個元素,你可以使用LINQ FirstOrDefault:

var element = array.FirstOrDefault(e => e.MyField == "value"); 

這如果沒有找到這樣的值,將返回滿足條件或null(或其他類型的默認值)的第一個元素。

0

Select()用作投影(即數據轉換),而不是過濾器。如果你想過濾一組對象,你應該看看.Where(),Single(),First()等等。如果您想驗證某個屬性是否適用於集合中的Any或All元素,那麼也可以使用這些元素。

0

您可以使用Where子句來過濾列表

var list = someList.Where(x => x.Name == "someName").FirstOrDefault(); 
var list = someList.Where(x => x.Name == "someName").ToList(); 

使用FirstOrDefault只選擇一個對象,並使用ToList選擇匹配你定義一個標準的多個對象。

並確保比較strings或者比較全部UppperCaseLowerCase字母。

var list = someList.Where(x => x.Name.ToUpper().Equals("SOMENAME")).FirstOrDefault(); 
1

我不是100%,如果我理解你的追問,但我會盡量嘗試回答這個問題: 如果你想只得到與所需領域的第一個對象,你可以使用FirstOrDefault:

var element = myArray.FirstOrDefault(o => o.FirstField == "someString"); 

如果找不到元素,它將返回null。

如果你只是要檢查,如果你的數組中的某些對象的字符串相匹配,你可以用任何

bool found = myArray.Any(o => o.FirstField == "someString"); 

希望檢查此這有助於