首页 > 解决方案 > 如何复制两个相似的列表?

问题描述

我有两个清单。只有一个字段差异。如何彼此填写列表。

  [Serializable()] 
  public class Lst1
  {
        public string filed1 { get; set; }
        public Int16 filed2 { get; set; }
        .
        .
        .
        public Boolean filed100 { get; set; } 
  }

  [Serializable()] 
  public class Lst2
  {
        public string filed1 { get; set; }
        public Int16 filed2 { get; set; }
        .
        .
        .
        public Boolean filed100 { get; set; } 
        public string filed101 { get; set; }  
  }

List<Lst1> Lst1_ = new List<Lst1>();
List<Lst2> Lst2_ = new List<Lst2>();

我从文件中填写清单。然后,我需要从列表一中填写列表二,有很多字段并且我不想使用 foreach 循环。

应该记住,我之前的课程已经构建并序列化并存储在一个文件中。现在我需要将之前的信息转移到第二类结构中。

我不想使用这个循环!

foreach (var t in Lst1_)
            {
                Lst2_.Add(new lst2
                {
                    filed1 = t.filed1,
                    filed2 = t.filed2,
                    .
                    .
                    .
                    filed100 = t.filed100,
                    filed101 = "kk"
                }
            }

标签: c#linq

解决方案


这是你想要的吗?

class Lst1
{
    public string filed1 { get; set; }
    public string filed2 { get; set; }
    public string filed3 { get; set; }
    public string filed4 { get; set; }
    public string filed5 { get; set; }
}

class Lst2
{
    public string filed1 { get; set; }
    public string filed2 { get; set; }
    public string filed3 { get; set; }
    public string filed4 { get; set; }
    public string filed5 { get; set; }
    public string filed6 { get; set; }
}

void CopyData()
{
        // test data
        List<Lst1> Lst1_ = new List<Lst1>()
        {
            new Lst1()
            {
                filed1 = "1",
                filed2 = "2",
                filed3 = "3",
                filed4 = "4",
                filed5 = "5",
            },
            new Lst1()
            {
                filed1 = "6",
                filed2 = "7",
                filed3 = "8",
                filed4 = "9",
                filed5 = "10",
            },
        };

        List<Lst2> Lst2_ = new List<Lst2>();

        foreach (var item in Lst1_)
        {
            Type type1 = item.GetType();
            PropertyInfo[] properties1 = type1.GetProperties();

            var current = new Lst2();
            Type type2 = current.GetType();
            PropertyInfo[] properties2 = type2.GetProperties();

            int k = 0;
            foreach (PropertyInfo property in properties1)
            {
                var value = property.GetValue(item, null);

                int n; 
                bool isNumeric = int.TryParse(value.ToString(), out n); 
                if (!isNumeric) 
                    value = "Your desired value"; 

                properties2[k].SetValue(current, value);
                k++;
            }

            Lst2_.Add(current);
        }
}

它将列表 1 中的所有内容复制到列表 2。


推荐阅读