2

I have two classes that are atm that same and defined cast:

 public static implicit operator SponsoredBrandViewModel(SponsoredBrand sponsoredBrand)
        =>
            new SponsoredBrandViewModel
            {
                Id = sponsoredBrand.Id,
                BrandId = sponsoredBrand.RelatedEntityId,
                To = sponsoredBrand.To,
                From = sponsoredBrand.From,
                Importance = sponsoredBrand.Importance
            };
    public static implicit operator SponsoredBrand(SponsoredBrandViewModel sponsoredBrandViewModel)
        =>
            new SponsoredBrand
            {
                Id = sponsoredBrandViewModel.Id,
                RelatedEntityId = sponsoredBrandViewModel.BrandId,
                To = sponsoredBrandViewModel.To,
                From = sponsoredBrandViewModel.From,
                Importance = sponsoredBrandViewModel.Importance
            };

I want to make it cast when it's a array.

ar dbSponsoredBrands = await this._sponsoredBrandRepository.GetAsync();
            var viewModels = (IEnumerable<SponsoredBrandViewModel>) dbSponsoredBrands.ToEnumerable();

But this throwing invalidcast exception.

Any ideas?

2 Answers 2

2

You're trying to cast the collection object IEnumerable<SponsoredBrand> into an IEnumerable<SponsoredBrandViewModel> where you've defined your implicit cast operator for the actual object. You'll need to iterate through the collection and create a new one, e.g.

var dbSponsoredBrands = await this._sponsoredBrandRepository.GetAsync();
var viewModels = dbSponsoredBrands.Select(x => (SponsoredBrandViewModel)x);
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, so no option to do it without iterating.
Correct, each object must be individually cast. If iterating presents a performance issue, you could take a lazy approach to the cast and defer it to when each viewmodel is used rather than all at once. Look into Enumerable.Cast<TResult> for more information.
0

You can use the LINQ-Functions

.Cast<SponsoredBrandViewModel>()

or

.OfType<SponsoredBrandViewModel>()

to achieve that. These will iterate over the result too, but in a lazy way. Use the first one if you are sure every element is of this type, the later one if you want to filter only the matching elements.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.