Make Distinct Entity Framework

Asked

Viewed 180 times

1

I’m trying to accomplish the Distinct, in my model of Phones, but none of the options I’m trying to make work. Could tell me what I’m doing wrong ?

Below I described several ways I have tried to do, but none of them worked for me, could give me a light ?

model.Phones = model.Phones.Where(x => x != null && x.Phone != null).ToList();
1ª - model.Phones = (from p in model.Phones select p).Distinct().ToList();
2ª - model.Phones = model.Phones.Select(a => a).Distinct().ToList();

I tried it both ways above, nothing else works.

Example of how I receive the data below:

inserir a descrição da imagem aqui

I’ve tried to do it this way:

model.Phones = model.Phones.Select(x => x.Phone).Distinct().ToList();

I get following error:

Cannot implicitly convert type 'System.Collections.Generic.List<string>' to 'System.Collections.Generic.List<KonBase.Areas.Admin.Models.ApplicationCondominiumViewModels.PhoneViewModel>'

And:

model.Phones = model.Phones.GroupBy(x => x.Phone).ToList();

I get following error:

Cannot implicitly convert type 'System.Collections.Generic.List<System.Linq.IGrouping<string, KonBase.Areas.Admin.Models.ApplicationCondominiumViewModels.PhoneViewModel>>' to 'System.Collections.Generic.List<KonBase.Areas.Admin.Models.ApplicationCondominiumViewModels.PhoneViewModel>'

  • Does your phone model only have the string attribute? If you have more than one and they have different ones, it’s no use just giving distinct

  • Yes, they have only string

1 answer

1

I just found out, actually by comparing the objects the distinct does not evaluate them as being equal. Some alternatives are: Group by:

List<Phones> teste = Phones.GroupBy(x=>x.Phone).ToList();

Select in field(will return a list of strings) before distinct

List<String> teste = Phones.Select(a => a.nome).Distinct().ToList();
  • Friend neither of the two options served for me I get the following errors: In the first option Cannot implicitly convert type 'System.Collections.Generic.List<System.Linq.IGrouping<string, KonBase.Areas.Admin.Models.ApplicationCondominiumViewModels.PhoneViewModel>>' to 'System.Collections.Generic.List<KonBase.Areas.Admin.Models.ApplicationCondominiumViewModels.PhoneViewModel>'&#xA;

  • And in the second option : Cannot implicitly convert type 'System.Collections.Generic.List<string>' to 'System.Collections.Generic.List<KonBase.Areas.Admin.Models.ApplicationCondominiumViewModels.PhoneViewModel>'&#xA;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.