Home > Software engineering >  How to cast object within a C# System.Linq lambda expression?
How to cast object within a C# System.Linq lambda expression?

Time:08-15

            List<System.Guid> meshGuidList= new List<System.Guid>();
            foreach (TreeGridItem meshcol in TerrainData.MeshCollection)
            {
                Globals.MeshProperty meshprop = meshcol.Tag as Globals.MeshProperty;
                meshGuidList.Add(meshprop.MeshGuid);
                }

I have a collection, in order to access it, I need to cast the items as TreeGridItem.

After casting the items, I need to cast meshcol.Tag again as Globals.MeshProperty so i can access it. Basically I want a list of meshprop.MeshGuid using Simple .Select function.

But the multiple casting feels a bit difficult.

CodePudding user response:

It is unclear what the Type is that is returned from the MeshCollection enumerator, but this syntax may work for you if all of the items in the collection can be cast to TreeGridItem

List<System.Guid> meshGuidList = TerrainData.MeshCollection
                     .Cast<TreeGridItem>()
                     .Select(mesh => (mesh.Tag as Globals.MeshProperty).MeshGuid)
                     .ToList();

_You could split that Select clause out to multiple lines if you wanted, but I'm not sure we gain much in readability or performance:

List<System.Guid> meshGuidList = TerrainData.MeshCollection
                     .Cast<TreeGridItem>()
                     .Select(mesh => mesh.Tag)
                     .Cast<Globals.MeshProperty>()
                     .Select(prop => prop.MeshGuid)
                     .ToList();
  •  Tags:  
  • c#
  • Related