2015-07-13 36 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"); 

希望检查此这有助于