【问题标题】:How do I combine columns together如何将列组合在一起
【发布时间】:2013-02-15 21:35:29
【问题描述】:

我有 2 个包含不同数据但具有相似列的列表。 基本上我想加入这些列表,然后将相似的列合并到 1 中。

var listCombo= List1.Where(a=>DataIds.Contains(a.dataId)).DefaultIfEmpty()
    .Join(List2,
    list1 => list1.key,
    list2 => list2.key,
    (L1,L2) => new
    {
        L2.key,
        L2.dataId,
        L2.dataValue,
        L2.date,
        L1.secId,
        L1.dataId,
        L1.dataValue
    });

我想将 dataId 和 dataValue 列组合在一起。我该怎么做?

所以我可以只说 listCombo.dataId 或 listCombo.dataValue 而不必唯一地命名它们。

【问题讨论】:

    标签: linq lambda


    【解决方案1】:

    如果我理解您的问题,您正在尝试将这两个字段合二为一。假设你有一个Class

    public class List1 {
    public int dataId {get;set;}
    public string dataValue {get;set;}
    public string combinedValue {get;set;}
    }
    

    不,你可以用like,

    var listCombo= List1.Where(a=>DataIds.Contains(a.dataId)).DefaultIfEmpty()
        .Join(List2,
        list1 => list1.key,
        list2 => list2.key,
        (L1,L2) => new List1
        {
           dataId = L2.dataId,
           dataValue = L2.dataValue
           combinedValue =  L2.dataId + " - " L2.dataValue
        });
    

    【讨论】:

      【解决方案2】:

      我会对 list1、list2 和第三个列表使用 POCO 方法,第三个列表是两者的组合。我敢肯定,如果您正在组合不同的类型,您会进行适当的强制转换,或者如果您想要复杂的类型,您可以将它们定义为它们自己的属性,或者不是。

       static void Main(string[] args)
              {
                  List<A> lisA = new List<A> {new A {AId = 1, AName = "Brett"}, new A {AId = 2, AName = "John"}};
                  List<B> lisB = new List<B> {new B { BId = 1, BName = "Doe" }, new B { BId = 2, BName = "Howard" } };
      
                  List<C> lisC = lisA.Join(lisB,
                                           list1 => list1.AId,
                                           list2 => list2.BId,
                                           (L1, L2) => new C
                                               {
                                                   CId = L1.AId,
                                                   CName = L1.AName + " " + L2.BName
                                               }).ToList();
      
                  lisC.ForEach(
                      n => Console.WriteLine(n.CName + "\n")
                      );
      
              }
      
              public class A
              {
                  public int  AId { get; set; }
                  public string AName { get; set; }
              }
      
              public class B
              {
                  public int BId { get; set; }
                  public string BName { get; set; }
              }
      
              public class C
              {
                  public int CId { get; set; }
                  public string CName { get; set; }
              }
      

      【讨论】:

        猜你喜欢
        • 2020-05-29
        • 1970-01-01
        • 2011-12-04
        • 1970-01-01
        • 2021-12-03
        • 2021-10-18
        • 1970-01-01
        • 1970-01-01
        • 2011-05-07
        相关资源
        最近更新 更多