开发者

Class associations and lists

开发者 https://www.devze.com 2023-01-06 12:25 出处:网络
I have a little C# 开发者_开发百科problem. I have two classes ClassA and ClassB defined in this way :

I have a little C# 开发者_开发百科problem. I have two classes ClassA and ClassB defined in this way :

public class ClassA
{
    private ClassB b;
    ClassB B;
    {
        get { return b; }
        set { b = value; }
    }
}

public class ClassB
{
    /* some stuff */
}

As you can see, ClassA has an instance of ClassB.

The thing is, from a list of ClassA instances, I want to access to a list of the corresponding ClassB instances. I suppose it would look like this:

IList<ClassA> listA = ...;
IList<ClassB> listB = listA.???.B;

The solution is probably obvious but I can't figure it out by myself.

Any help would be appreciated !


You could use LINQ to do

IList<ClassB> listB = listA.Select(a => a.B).ToList();


Using List.ConvertAll():

List<ClassA> listA = ...;
List<ClassB> listB = listA.ConvertAll(item => item.B);


You could easily do this with LINQ to Objects in one of the following ways:

var instancesOfClassB = from a in listOfClassA
                        select a.B;

var instancesOfClassB = listOfClassA.Select(a => a.B);


You could do this:

IList<B> listB = listA.ConvertAll(a => a.B);

which is simple and says what it does.

0

精彩评论

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