For some reason, i need to copy only view details from one list into another list.
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;}
}
Here, in runtime, I will get all the details for the c1 class, and I need to store only 2parameters to store into c2. How can i achieve this? I tried below, but its not working!!
dynamic d=from a in c1
select new
{
a.id,
a.firstname
};
List<c2> c2list=d;
Use ToList method https://docs.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();
Here is a basic example:
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; }
}
This outputs them into a list as follows:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.