开发者

Setting List<CustomObject> = List<String> - having a brain dead moment

开发者 https://www.devze.com 2023-02-01 12:16 出处:网络
I\'m sure this is easy. Infact I\'m sure I\'ve done this before... I have a class of MyClass which has 2 parameters T开发者_Python百科heString and SomeInt

I'm sure this is easy. Infact I'm sure I've done this before...

I have a class of MyClass which has 2 parameters T开发者_Python百科heString and SomeInt

Somewhere, in another class I declare an List<MyClass> MyClassList and a List<String> StringList

Both have the same number of items. I want this to set all "TheStrings" in each MyClass from MyClassList equal to the corresponding String from StringList

I set MyClassList = StringList

Now I know this wont work because they're different types. I think I've got to overload the assignment (=) operator but I can't see how this is done. I suppose I could always provide a method to call from MyClass, but that isn't quite so elegant. What would be the most elegant solution?

Thanks Thomas


You can't overload the = operator. You could do an implicit conversion, example from MSDN:

public static implicit operator double(Digit d)
{
   return d.val;
}

However in case of lists I think the best solution is to use LINQ:

List<MyClass> list = (from value in StringList
                     select new MyClass { TheString = value }).ToList();


Nowhere near enough information, but:

var customObjects = new List<CustomObject>(TheStringList.Select(s => new CustomObject { TheString = s }));

I didn't test this, but I wanted to show the idea that came to mind.


It seems you're looking for elegance and quite possibly magic when it sounds like a simple for loop should suffice. You've described the problem as having two equally sized lists, one of a particular class, another of strings. You want to set a string property on each class to the corresponding string in the opposite list (so presumably these are sorted and at matching indexes). All you need is a loop.

for (int index = 0; index = MyClassList.Count; index++)
{
     MyClassList[index].TheString = StringList[index];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号