[英]Condition in linq select
我在兩個表之間有一個內部 linq 連接,如下所示:
(from A in table1 join B in table2
on A.name equals B.name
where {some condition}
select new {
A.name ,
A.color,
.
.
.
}).toList();
問題是在某些記錄中“名稱”是null並且我想要 linq 查詢將 null 替換為 Z99959282F041071中的“”。
像這樣的東西:
select new {
A.name!=null?A.name : " "
.
.
.
}
我怎樣才能做到這一點?
(我知道我可以有一個條件,我檢查不是null但在這種情況下它會跳過該記錄,但我想拿它並用字符串替換null名稱)
提前致謝;)
您可以使用空合並運算符??
以空字符串作為默認值。 然后將其結果分配給匿名類型的屬性
select new {
name = A.name ?? "",
//rest of code
}
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
// Student collection
IList<Student> studentList = new List<Student>() {
new Student() { StudentID = 1, StudentName = null, Age = 13} ,
new Student() { StudentID = 2, StudentName = "Moin", Age = 21 } ,
new Student() { StudentID = 3, StudentName = "Bill", Age = 18 } ,
new Student() { StudentID = 4, StudentName = "Ram" , Age = 20} ,
new Student() { StudentID = 5, StudentName = "Ron" , Age = 15 }
};
// LINQ Query Syntax to find out teenager students
var teenAgerStudent = (from s in studentList
where s.Age > 12 && s.Age < 20
select new {Name=s.StudentName??"Tuna"}).ToList();
Console.WriteLine("Teen age Students:");
foreach(var std in teenAgerStudent){
Console.WriteLine(std.Name);
}
}
}
public class Student{
public int StudentID { get; set; }
public string StudentName { get; set; }
public int Age { get; set; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.