Linq---元素运算符/Element Operators

以下代码均来自微软官网

获取某一个单一元素
---First         //获取第一个元素


---FirstOrDefault    //获取第一个元素(当第一个元素为null或为空时,自动根据其数据类型给一个默认值)


---ElementAt         

//根据索引获得一个元素

e.g
///


/// First
///

public void Linq1()
{
    string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
    string startsWithO = strings.First(s => s[0] == 'o');
    Console.WriteLine("A string starting with 'o': {0}", startsWithO);
}

---result
A string starting with 'o': one


///


/// FirstOrDefault(获得第一个元素,自动为其创建默认值)
///

public void Linq2()
{
    int[] numbers = { };
    int firstNumOrDefault = numbers.FirstOrDefault();
    Console.WriteLine(firstNumOrDefault);
}

---result
0

///


/// ElementAt(获得大于5的第二个数)
///

public void Linq3()
{
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
    int fourthLowNum = (
        from n in numbers
        where n > 5
        select n)
        .ElementAt(1);  // second number is index 1 because sequences use 0-based indexing
    Console.WriteLine("Second number > 5: {0}", fourthLowNum);
}

---result
Second number > 5: 8

你可能感兴趣的:(LINQ,C#,numbers,linq,string,null,微软)