【问题标题】:Condition in linq selectlinq 选择中的条件
【发布时间】:2020-08-01 22:05:41
【问题描述】:

我在 2 个表之间有一个内部 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();

问题是在某些记录中 "name"null 并且我希望 linq 查询在选择部分用“”替换 null .

类似这样的:

select new {
A.name!=null?A.name : " "
.
.
.
}

我该怎么做?

(我知道我可以在 where 中有一个条件,我检查不是 null 但在这种情况下它将跳过该记录但我想取它并替换null 名称和字符串)

提前致谢;)

【问题讨论】:

标签: c# asp.net .net linq join


【解决方案1】:

您可以使用带有空字符串的null-coalescing operator ?? 作为默认值。然后将其结果分配给匿名类型的属性

select new { 
    name = A.name ?? "",
    //rest of code
}

【讨论】:

    【解决方案2】:

    Sample

    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; }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2013-08-17
      • 1970-01-01
      • 2012-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多