为每一行添加两个条目 - Linq C#

时间:2017-06-18 05:51:07

标签: c# linq

这是我的疑问:

from customer in db.tblCustomers
select new
{
     ID = customer.CustomerID,
     Mobile = customer.Mobile1,
     LastName = customer.Family
};

对于每个客户都有两部手机,如果第二部手机不是空的,我需要添加一个新的条目。我也应该将第二个条目的LastName更改为“Second Mobile”。如何使用linq查询从一个客户获得两个不同的条目?

2 个答案:

答案 0 :(得分:2)

使用相同的生成类型,您不能只拥有一个电话号码属性,另一个只有两个属性。你可以这样做:

from customer in db.tblCustomers
select new
{
     ID = customer.CustomerID,
     Mobile = customer.Mobile1,
     SecondMobile = customer.Mobile2, // will be null if no second mobile exists
     LastName = customer.Family
};

否则,你可以做的是创建一个自定义类型Customer,它将包含一个电话号码和一个带有两个的派生类型ExtendedCustomer - 并且只是实例化其中一个。 psudo上的东西:

from customer in db.tblCustomers
select customer.Mobile2 != null ? new Customer(...) : new ExtendedCustomer(...);

如果你的意思是在结果集合中有两个不同的对象,那么使用union:

List<Customer> result = new List<Customer>();
foreach(var item in db.tblCustomers)
{
    result.Add(new Customer(/*data for first mobile phone*/);
    if(item.Mobile2 != null) 
    {
        result.Add(new Customer(/*data for second mobile phone*/);
    }
}

答案 1 :(得分:2)

如果有帮助,请你试试吗?

var customers = db.tblCustomers.SelectMany(x => x.GetMultipleRow()).ToList();

GetMultipleRow是一种扩展方法,如下所示。

public static class CustomerExtensions
{
    public static IEnumerable<Customer> GetMultipleRow(this Customer cust)
    {
        yield return new Customer { CustomerID = cust.CustomerID, Mobile1 = cust.Mobile1, Family = cust.Family };
                                    /* Data for first mobile*/
        if (cust.Mobile2 != null)
            yield return new Customer { CustomerID = cust.CustomerID, Mobile1 = cust.Mobile2, Family = cust.Family };
                                        /* Data for second mobile*/
    }
}