选择lambda用法

本文关键字:用法 lambda 选择 | 更新日期: 2023-09-27 18:02:20

对不起,也许是新手问题),但我只是想学习一些新的东西。我有一个数组,持有对象与许多领域-如何用select检查这个对象的第一个字段是否等于某个字符串?(这个字段也是一个字符串,所以不需要类型操作)

选择lambda用法

考虑这个场景:

// 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.

我不是100%,如果我理解你的问题,但我会尽量回答它:如果你只想获得第一个对象与所需的字段,你可以使用FirstOrDefault:

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

如果没有找到该元素,则返回null。

如果你只想检查数组中的某个对象是否与字符串匹配你可以使用任意

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

希望能有所帮助

如果你只是想在一个字段/属性中找到数组中具有特定值的第一个元素,你可以使用LINQ FirstOrDefault:

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

如果没有找到满足条件或null(或类型的其他默认值)的第一个元素。

Select()用作投影(即数据转换),而不是用作过滤器。如果你想过滤一组对象,你应该看看。where (), Single(), First()等。如果您想要验证属性是否适用于集合中的Any或All元素,您也可以使用它们。

您可以使用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();