foreach具有必须由两个变量检查​​的where和condition参数

时间:2018-10-04 10:10:57

标签: c# linq foreach

我正在使用2个变量Dname和Gname查询通过控制器2名称的学生的列表。在Dname中,某些名称以D字母开头,在Gname中,某些名称以G字母开头。

innerJoinQuery.Where(item => 
    (string.IsNullOrWhiteSpace(Dname) || item.StudentName== Dname) 
    && 
    (string.IsNullOrWhiteSpace(Gname) || item.StudentName== Gname)
)

条件是:如果我不输入任何姓名,我将获得整个学生名单。 有效

如果仅通过Dname,我会得到以D开头的学生名单。有效

如果仅通过Gname,我将获得以G开头的学生名单。有效

但是,如果我同时传递两个变量,那么我将一无所获。但是我想获得以Dname var和Gname var开头的名字的学生列表。我该怎么做?

更新

如果我使用此代码:

        (string.IsNullOrWhiteSpace(Dname) && string.IsNullOrWhiteSpace(Gname ) 
    || item.StudentName.ToString() == Dname.ToString() ||
item.StudentName.ToString() == Gname.ToString())

仅发送Dname,然后出现异常:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

Gname was null.

1 个答案:

答案 0 :(得分:1)

不告诉您要走的路,但这符合您的要求:

using System;
using System.Linq;
using System.Collections.Generic;

public class Student
{
    public int Id {get;set;}
    public string Name {get;set;}
}

class Program
{
    static List<Student> Students {get;set;}

    static void Main()
    {
        Students = new List<Student>
        {
            new Student{ Id = 1, Name = "G"},
            new Student{ Id = 2, Name = "D"},
            new Student{ Id = 3, Name = "G"},
            new Student{ Id = 4, Name = "G"},
            new Student{ Id = 5, Name = "D"},
            new Student{ Id = 6, Name = "E"},
            new Student{ Id = 7, Name = "F"},
            new Student{ Id = 8, Name = "G"},
            new Student{ Id = 9, Name = "H"}
        };

        WriteStudents(null, null); // 1,2,3,4,5,6,7,8,9
        WriteStudents(null, "D");  // 2,5
        WriteStudents("G", null);  // 1,3,4,8
        WriteStudents("G", "D");   // 1,2,3,4,5,8
    }

    static void WriteStudents(string GName, string DName)
    {
        var query = Students.Where(s => string.IsNullOrWhiteSpace(GName)
                                     && string.IsNullOrWhiteSpace(DName)
                                     || s.Name == GName || s.Name == DName)
                            .Select(s => s.Id); // used to print the Id

        Console.WriteLine(string.Join(",", query));
    }
}

很明显,可以将WriteStudents方法编写为:

static void WriteStudents(string first = null, string second = null)
{
    var query = Students.Where(s => string.IsNullOrWhiteSpace(first)
                                 && string.IsNullOrWhiteSpace(second)
                                 || s.Name == first || s.Name == second)
                        .Select(s => s.Id); // used to print the Id

    Console.WriteLine(string.Join(",", query));
}

所以您可以这样称呼:

WriteStudents();         // 1,2,3,4,5,6,7,8,9
WriteStudents("D");      // 2,5
WriteStudents("G");      // 1,3,4,8
WriteStudents("G", "D"); // 1,2,3,4,5,8