如何在LINQ中的select中添加where子句?

时间:2013-06-17 09:02:36

标签: c# .net linq

我有以下内容:

var result =
    from entry in feed.Descendants(a + "entry")
    let content = entry.Element(a + "content")
    let properties = content.Element(m + "properties")
    let text = properties.Element(d + "Text")
    let title = properties.Element(d + "Title")
    let partitionKey = properties.Element(d + "PartitionKey")
    select new Content
    {
        Text = text.Value,
        Title = title.Value
    };

我想要做的是添加一个位置,以便只将一些项目放入结果中。我该如何添加条件:

partitionKey.Substring(2, 2) == "03" && text != null

选择?

5 个答案:

答案 0 :(得分:2)

只需在选择前添加条件:

var result =
    from entry in feed.Descendants(a + "entry")
    let content = entry.Element(a + "content")
    let properties = content.Element(m + "properties")
    let text = properties.Element(d + "Text")
    let title = properties.Element(d + "Title")
    let partitionKey = properties.Element(d + "PartitionKey")
    where partitionKey.Value.Substring(2, 2) == "03"
    where text != null
    select new Content
    {
        Text = text.Value,
        Title = title.Value
    };

答案 1 :(得分:2)

而不是

where partitionKey.Substring(2, 2) == "03" && text != null

使用

where partitionKey.Value.Substring(2, 2) == "03" && text != null

partitionKey的类型为XElement,当您需要它的值时。

答案 2 :(得分:1)

where

之前指定select
var result =
    from entry in feed.Descendants(a + "entry")
    let content = entry.Element(a + "content")
    let properties = content.Element(m + "properties")
    let text = properties.Element(d + "Text")
    let title = properties.Element(d + "Title")
    let partitionKey = properties.Element(d + "PartitionKey")
    where partitionKey.Substring(2, 2) == "03" && text != null
    select new Content
    {
        Text = text.Value,
        Title = title.Value
    };

答案 3 :(得分:1)

        var result =
from entry in feed.Descendants(a + "entry")
let content = entry.Element(a + "content")
let properties = content.Element(m + "properties")
let text = properties.Element(d + "Text")
let title = properties.Element(d + "Title")
let partitionKey = properties.Element(d + "PartitionKey")
where partitionKey.Value.Substring(2, 2) == "03" && text != null
select new Content
{
    Text = text.Value,
    Title = title.Value
};

答案 4 :(得分:0)

我建议使用linquer软件将SQL脚本转换为LINQ,想象一下在Inner Joins和更多complecx查询时?

访问:www.sqltolinq.com/

这是非常方便的工具!!