T
T
TeVeTed2016-06-12 13:37:36
ASP.NET
TeVeTed, 2016-06-12 13:37:36

How to deal with many-to-many relationship in a controller?

I operate with one-to-many relationships in the controller, it's all the same type

public ViewResult List(string region,
                               string area,
                               string localityType,
                               string speciality,
                               int page = 1)
        {
            CollegeListViewModel model = new CollegeListViewModel
            {
                Colleges = repository.Colleges
                .Where(p => region == null || p.Area.Region.Name == region)
                .Where(p => localityType == null || p.LocalityType.Name == localityType)
                .Where(p => area == null || p.Area.Name == area)
                .OrderBy(college => college.CollegeId)
                .Skip((page - 1) * pageSize)
                .Take(pageSize),
                PagingInfo = new PagingInfo
                {
                    CurrentPage = page,
                    ItemsPerPage = pageSize,
                    TotalItems = ((region == null) && (localityType == null)) ?
                repository.Colleges.Count() :
                repository.Colleges.Where(college => college.Area.Region.Name == region)
                                   .Where(college => college.Area.Name == area)
                                   .Where(college => college.LocalityType.Name == localityType).Count()
                },
                CurrentRegion = region,
                CurrentArea = area,
                CurrentLocalityType = localityType,
            };
            return View(model);
        }

All .Where(...) compare string and string, and I need to add another .Where(...) where the List element and string specialty will be compared .
help me please

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sanostee, 2016-06-12
@andrewpianykh

How can a string be compared to a list of strings?
Use the Contains and Count methods to check if a string is in a list.

var list = new List<string>() { "one", "two", "three", "four" };
var expected = "two";
var result = list.Contains(expected);
// либо
result = list.Count(a => a == expected) > 0;

In your case, for example:
var regions = new List<string>() { "region 1", "region 2", "region 3", "region 4" };
repository.Colleges.Where(college => regions.Count(a =>  a == college.Area.Region.Name) > 0);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question