linq 将一种类型的列表〈>复制到另一种类型的列表〈>

velaa5lx  于 2022-12-06  发布在  其他
关注(0)|答案(2)|浏览(201)

出于某种原因,我只需要将视图详细信息从一个列表复制到另一个列表中。

public class c1
{
public string id{get;set;}
public string firstname{get;set;}
public string lastname{get;set;}
public string category{get;set;}
public string gender{get;set;}
}

public class c2
{
public string id{get;set;}
public string firstname{get;set;}
}

在这里,在运行时,我将获得c1类的所有细节,我只需要存储2个参数就可以存储到c2中。我如何才能做到这一点?我尝试了下面的方法,但它不起作用!!

dynamic d=from a in c1 
      select new   
      {
       a.id,
       a.firstname
      };

List<c2> c2list=d;
klsxnrf1

klsxnrf11#

使用ToList方法https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.tolist?view=net-6.0

List<c2> list2 = (from a in c1 
                  select new c2  
                  {
                      a.id,
                      a.firstname
                  }).ToList();
oewdyzsn

oewdyzsn2#

下面是一个基本示例:

void Main()
{
    List<c1> c1List = new List<c1>();
    List<c2> c2List = new List<c2>();
    
    c1 example1 = new c1 {
        category = "some category",
        firstname = "John",
        gender = "some gender",
        id = "1",
        lastname = "Smith",
    };
    
    c1List.Add(example1);

    c2List.AddRange(c1List.Select(x => new c2 {
        firstname = x.firstname,
        id = x.id
    }));
    

    
}

// You can define other methods, fields, classes and namespaces here

public class c1
{
    public string id { get; set; }
    public string firstname { get; set; }
    public string lastname { get; set; }
    public string category { get; set; }
    public string gender { get; set; }
}

public class c2
{
    public string id { get; set; }
    public string firstname { get; set; }
}

这会将它们输出到列表中,如下所示:

相关问题