使用Linq过滤表数据

时间:2019-05-20 10:49:29

标签: linq

我要过滤下表中 TO 值不等于任何类型的 FROM 值的类型为 X 的邮件Y 记录在同一表中。 (例如ee)使用Linq。

   Message     TO       FROM       Type
   -------    ----     -----      ------
    aa          11       22          X
    bb          33       44          X
    cc          55       11          Y
    dd          66       33          Y
    ee          77       88          X    

我已经用过了,但是没用

var messages1 = messages.Where(x => x.Type == 'X');

var messages2 = messages.Where(x => x.Type == 'Y');

var filteredMessages = messages1
                .Where(x => !messages2.Any(y => y.From == x.To));

1 个答案:

答案 0 :(得分:0)

尽管我得到正确的输出,但我无法重现您的问题。

private static void Main(string[] args)
{
    List<MessageItem> messages = new List<MessageItem>
    {
        new MessageItem
        {
            Message = "aa",
            From = 22,
            To = 11,
            Type = "X"
        },
        new MessageItem
        {
            Message = "bb",
            From = 44,
            To = 33,
            Type = "X"
        },
        new MessageItem
        {
            Message = "cc",
            From = 11,
            To = 55,
            Type = "Y"
        },
        new MessageItem
        {
            Message = "dd",
            From = 33,
            To = 66,
            Type = "Y"
        },
        new MessageItem
        {
            Message = "ee",
            From = 88,
            To = 77,
            Type = "X"
        }
    };

    var messages1 = messages.Where(x => x.Type == "X").ToList();
    var messages2 = messages.Where(x => x.Type == "Y").ToList();
    var filteredMessages = messages1.FindAll(x => !messages2.Any(y => x.To == y.From));
}

模型类:

public class MessageItem
{
    public string Message { get; set; }
    public int From { get; set; }
    public int To { get; set; }
    public string Type { get; set; }
}

输出:

enter image description here