【问题标题】:add two entry for every row - Linq C#为每一行添加两个条目 - Linq C#
【发布时间】:2017-06-18 14:50:47
【问题描述】:

这是我的查询:

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

对于每个客户都有两部手机,如果第二部手机不为空,我需要添加一个新条目。我也应该将第二个条目的姓氏更改为“第二个手机”之类的东西。如何使用 linq 查询从一位客户那里获得两个不同的条目?

【问题讨论】:

    标签: c# linq


    【解决方案1】:

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

    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(...);
    

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

    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*/);
        }
    }
    

    【讨论】:

    • 正如您所说,他需要为第二个手机号码提供另一个字段或拥有 parentId 字段,无论哪种方式他所做的都是错误的。你是对的 =) 没关系。
    • 我认为它不能解决给定的问题。为什么接受?下面是正确的解决方案stackoverflow.com/a/44612471/5432796
    【解决方案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*/
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-11
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多