c#Linq List - 处理null

时间:2015-07-26 19:46:16

标签: c# linq

在第二个列表中我试图创建一个关系,但如果它不能匹配,我该如何忽略并且不添加项目?

var clientData = File.ReadAllLines(txtClients.Text)
                    .Skip(1)
                    .Select(x => x.Split(','))
                    .Select(x => new Client()
                    {
                        ClientTempId = x[0],
                        Email = x[1],
                        FirstName = x[2],
                        LastName = x[3],
                        AccountId = accountId
                    });

var orderData = File.ReadAllLines(txtOrders.Text)
                  .Skip(1)
                  .Select(x => x.Split(','))
                  .Select(x => new Order()
                  {
                      OrderTempId = x[0],
                     ClientId = clientData.FirstOrDefault(c=>c.ClientTempId == x[1]).Id ==string.Empty?"Error here!!":x[1],
                     //How do I handle errors, if client does not exist, or row is in wrong format? dont want to break code just want a list or issues
                      Name = x[3],
                      AccountId = accountId
                  });

1 个答案:

答案 0 :(得分:0)

您可以返回null,然后将其过滤掉:

var orderData = File.ReadAllLines(txtOrders.Text)
    .Skip(1)
    .Select(x => x.Split(','))
    .Select(x =>
    {
        // do your check here, and return null
        if (clientData.FirstOrDefault(c => c.ClientTempId == x[1]) == null)
            return null;

        // otherwise return the normal Order object
        return new Order()
        {
            OrderTempId = x[0],
            ClientId = x[1],
            Name = x[3],
            AccountId = accountId
        };
    })
    // then filter out null values
    .Where(x => x != null);

一旦涵盖了这一点,正如EZI在评论中指出的那样,您的实际支票非常昂贵。通过将clientData转换为字典,您可以提高效率:

var clientDataDictionary = clientData.ToDictionary(c => c.ClientTempId);

然后,您可以在恒定时间内执行上述查找:

if (clientDataDictionary.ContainsKey(x[1]))
    return null;