22

我在 c# 中有以下行:

var name = (from x in db.authors
                    where fullName == "Jean Paul Olvera"
                    orderby x.surname
                    select new { x.id_author, fullName= String.Concat(x.name," ", x.surname) });

我的问题是我想在 where 子句中使用别名,但我不能,'fullName' 显示为未声明。

4

6 回答 6

41

您可以使用let创建中间值:

var name = (from x in db.authors
            let fullName = x.name + " " + x.surname
            where fullName == "Jean Paul Olvera"
            orderby x.surname
            select new { x.id_author, fullName });
于 2013-04-09T16:07:16.300 回答
10

您需要更早地放置投影的那一部分,这很容易使用let子句

var name = from x in db.authors
           let fullName = x.name + " " + x.surname
           where fullName == "Jean Paul Olvera"
           orderby x.surname
           select new { x.id_author, fullName };

请注意,x.name + " " + x.surname它将被编译为与 相同的代码String.Concat(x.name, " ", x.surname),但对大多数人来说更具可读性。另请注意,由于您没有在()括号之外做任何事情,因此不需要它们。

希望任何优秀的 SQL LINQ 提供程序都应该将此查询转换为明智且高效的 SQL 查询,但您应该自己验证这一点。另一方面,我通常建议优先查询单个字段,例如

where x.name == "Jean Paul" && x.surname == "Olvera"
于 2013-04-09T16:07:30.077 回答
6

你还没有创建它。

话虽如此,由于您事先知道名称,因此您应该能够对零件执行查询:

var name = from x in db.authors
                where name == "Jean Paul" && surname == "Olvera"
                orderby x.surname
                select new { x.id_author, fullName= String.Concat(x.name," ", x.surname) };

否则,您可以使用它let来执行此操作:

var name = from x in db.authors
           let fullName = String.Concat(x.name," ", x.surname)
           where fullName == "Jean Paul Olvera"
           orderby x.surname
           select new { x.id_author, fullName=fullName ) };
于 2013-04-09T16:06:53.873 回答
4

方法语法更容易,因为您不受操作顺序的限制:

var query = authors.OrderBy(x => x.surname)
    .Select(x => new
    {
        x.id_author,
        fullName = String.Concat(x.name, " ", x.surname)
    })
    .Where(x => x.fullName == "Jean Paul Olvera");
于 2013-04-09T16:08:24.973 回答
4
linq1DataContext ll = new linq1DataContext();
            if (comboBox1.SelectedIndex == 0)
            {

                var q = from m in ll.personals                            



                        let کد= m.id
                        let نام = m.name

                        select new { 
                                     کد,
                                     نام,
                        };
                dataGridView1.DataSource = q;
            }
于 2014-06-08T13:06:19.217 回答
2

使用let子句:

var name = (from x in db.authors
                let fullName = String.Concat(x.name," ", x.surname)
                where fullname = "Jean Paul Olvera"
                orderby x.surname
                select new { x.id_author, fullName });
于 2013-04-09T16:07:39.593 回答