繁体   English   中英

LINQ到SQL有两个条件

[英]linq to sql with two conditions

我想用两个where条件将linq to sql写入linq to sql查询,但是在所有条件下都将select不同的选择。 (两列具有相同的类型,因此我将它们放入该列表没有问题。)

我想使其看起来像正常情况:

    if (...)
          // do something - select one column
    if (...)
          // do something - select another column

现在,我以这种方式写了:( A是传递给函数的Parameter,我检查A是否为列之一-如果是,请选择另一列)

        var q1 = from stud in _context.temps
                where stud.a == A // this is first condition A==a
                select stud.b; // here selected column b
        var q2 = from stud in _context.temps
                where stud.b == A // this is second condition A==b
                select stud.a; // here selected column a
        List<temp> answer = q1.ToList();
        answer.AddRange(q2.ToList());
        return answer;

但这似乎太复杂了。

你的意思是:

IQueryable<string> query;
if(foo) {
    query = from row in db.SomeTable
            where row.Whatever
            select row.SomeString;
} else if (bar) {
    query = from row in db.MaybeAnotherTable
            select row.AnotherString;
} ...

foreach(string s in query) ...

根据您的更新进行编辑:

如果你有

 IQueryable<string> query1 = ..., query2 = ...;
 IQueryable<string> result = null;

这样您可以有多个:

if(condition1) {
    result = result == null ? query1 : result.Concat(query1);
}
if(condition2) {
    result = result == null ? query2 : result.Concat(query2);
}

您可以在select子句中使用第三运算符 参见以下代码:

Dictionary<string, string> names = new Dictionary<string, string>();
names.Add("Saeed", "Neamati");
names.Add("Rasour", "Zabihi");
names.Add("Vahid", "Asefi");
names.Add("Mohsen", "Parmooz");

var query = from name in names
            select name.Key.StartsWith("V") ? name.Key : name.Value;
query.ToList().ForEach(n => {
    Console.WriteLine(n);
});
Console.ReadLine();

它产生的是:

Nemati
Zabihi
Vahid
Parmooz

查看您提供的示例,似乎您只需要一个联合即可。 如果是这样,下面的代码将是您想要的。

var q1 = (from stud in _context.temps
        where stud.a == A
        select stud.b).Union 
            (from studb in _context.temps
            where stud.b == A
            select stud.a);

List<temp> answer = q1.ToList();
return answer;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM