Reputation: 24067
I have two data types:
class MyDataType {
public int Id;
private int Field;
public String AnotherFieldOrProperty;
// + there are some methods
}
class MyDataTypeDescriptor {
public int Id;
public String Description;
}
I need to convert List<MyDataType>
to List<MyDataTypeDescriptor>
such a way:
MyDataTypeDescriptor.Id = MyDataType.Id
MyDataTypeDescriptor.Description = MyDataType.ToString()
;
I guess C# can do that very easy and fast in just one line of code, but I don't know how because I'm not familar with such advanced techniques. Would someone help me please?
Thanks
Upvotes: 2
Views: 137
Reputation: 6062
Just to add one more way
define an explicit user type conversion MSDN
then do
var newlist = MyDataTypleList.Cast<MyDataTypeDescriptor>().ToList();
Upvotes: 0
Reputation: 7105
You can't actually convert them, you'll have to iterate through the collection and create a new Descriptor for each DataType
var result = (from MyDataType m in listOfMyDataType select new MyDataTypeDescriptor
{
Id = m.Id,
Description = m.toString(),
}).ToList();
Upvotes: 0
Reputation: 6878
You can do this with LINQ
:
var listofMyDataTypeDescriptor = (from m in listOfMyDataType
select new MyDataTypeDescriptor()
{
Id = m.Id,
Description = m.ToString()
}).ToList();
Upvotes: 0
Reputation: 46047
For simple conversions, you can use the Select
method like this:
List<int> lstA = new List<int>();
List<string> lstB = lstA.Select(x => x.ToString()).ToList();
For more compex conversions, you the ConvertAll
function, like this:
List<int> lstA = new List<int>();
List<string> lstB = lstA.ConvertAll<string>(new Converter<int, string>(StringToInt));
public static string StringToInt(int value)
{
return value.ToString();
}
Upvotes: 0
Reputation: 18743
You can do it by using LINQ Select
method:
List<MyDataType> list;
// Process list...
List<MyDataTypeDescriptor> result =
list.Select(x => new MyDataTypeDescriptor() { Id = x.Id, Description = x.ToString() }).
ToList<MyDataTypeDescriptor>();
Or if you have a constructor for MyDataTypeDescriptor
that takes an Id
and a Description
:
List<MyDataType> list;
// Process list...
List<MyDataTypeDescriptor> result =
list.Select(x => new MyDataTypeDescriptor(x.Id, x.ToString())).
ToList<MyDataTypeDescriptor>();
Upvotes: 0
Reputation: 5190
You can use automapper to do this automagically for you if you don't want to write the iterator yourself..
Upvotes: 0
Reputation: 35793
This should do it (where myDataTypes
is your List<MyDataType>
):
List<MyDataTypeDescriptor> myDataTypeDescriptors =
myDataTypes.Select(x => new MyDataTypeDescriptor
{
Id = x.Id,
Description = x.ToString()
}).ToList();
Upvotes: 4
Reputation: 3951
(from i in list1
select new MyDataTypeDescriptor { Id = i.Id, Description = i.ToString()).ToList();
Upvotes: 0