I am having difficulty with a query.
string userId = User.Identity.GetUserId();
var houseViewModel = this.Data.Houses.All()
.Where(u => u.UserId == userId && u.Name == houseName)
.Select(h => new HouseViewModel
{
Id = h.Id,
Name = h.Name,
ImageUrl = h.ImageUrl,
FloorsViewModel = h.Floоrs.Where(f=>f.Id>0)
.Select(f => new FloorViewModel
{
Name = f.Name,
RoomViewModel = f.Rooms.Where(r => r.Id > 0)
.Select(r => new RoomViewModel
{
Id = r.Id,
Name = r.Name,
SensorViewModel = new SensorViewModel
{
Id = r.Sensor.Id,
CurrentTemp = r.Sensor.CurrentTemp,
},
})
})
})
.SingleOrDefault();
When he came to the room in which no sensor throws exception because Id for SensorViewModel is a non-nullable property.
SensorViewModel = new SensorViewModel
{
Id = r.Sensor.Id,
SensorViewModel = r.Sensor == null ? new SensorViewModel() : new SensorViewModel
{
Id = r.Sensor.Id,
CurrentTemp = r.Sensor.CurrentTemp,
},
next try. Simple select only rooms with sensor.
RoomViewModel = f.Rooms.Where(r => r.Id > 0 && r.Sensor != null)
.Select(r => new RoomViewModel
{
Id = r.Id,
Name = r.Name,
SensorViewModel = new SensorViewModel
{
Id = r.Sensor.Id,
CurrentTemp = r.Sensor.CurrentTemp,
},
})
last attempt, select data from EF into list and then make viewmodel
var house = this.Data.Houses.All()
.Where(u => u.UserId == userId && u.Name == houseName).ToList();
var houseViewModel = house.Select(h => new HouseViewModel
{
Id = h.Id,
Name = h.Name,
ImageUrl = h.ImageUrl,
FloorsViewModel = h.Floоrs.Where(f=>f.Id>0)
.Select(f => new FloorViewModel
{
Name = f.Name,
RoomViewModel = f.Rooms.Where(r => r.Id > 0)
.Select(r => new RoomViewModel
{
Id = r.Id,
Name = r.Name,
SensorViewModel =r.Sensor == null ? null : new SensorViewModel
{
Id = r.Sensor.Id,
CurrentTemp = r.Sensor.CurrentTemp,
},
})
})
})
.SingleOrDefault();
Related
I'm experiencing an odd issue .
I got both a text input search field, and a dropdown list.
I've set that with every change on the select menu it will submit said form with the values .
It does bind the values but it bypasses the OnSuccess function and then basically things fall apart
Relevant Code:
#Html.EnumDropDownListFor(x => x.AreaCodes, "בחר אזור", new
{
#class = "select_field w-select",
onchange = "this.form.submit()"
})
ReloadLocations = () => {
$.ajax({
url:`#Url.Action("LocationsList","Locations")`,
method: 'POST',
dataType: 'html',
contentType: 'charset=utf-8',
success: function (data) {
$("#LocationList").empty();
$("#LocationList").append(data);
},
In this version it submits the form, However it goes straight to the function without actually going into the "success" part of the ajax call,
Just returns a view.
which results in me getting a partial view back.
How can I fix this?
Edit:
Full Controller Methode:
{
public ActionResult LocationsList(SearchLocationVM searchVm)
var locationsVM = new List<LocationVM>();
var locations = new List<Locations>();
var searchTerm = searchVm.SearchTerm;
var searchArea = (int)searchVm.AreaCodes;
using (var unitOfWork = new UnitOfWork(new FriendsEntities()))
{
if (searchVm.AreaCodes == 0 && string.IsNullOrWhiteSpace(searchVm.SearchTerm))
{
locations = unitOfWork.Locations.Find(x => x.Visibility).OrderBy(x => x.Order).ToList();
locationsVM = locations.Select(x => new LocationVM()
{
ActivityHours = x.location_open_time ?? string.Empty,
ContactName = x.location_contact_name ?? string.Empty,
FirstPHone = x.first_phone_number ?? string.Empty,
SecondPHone = x.second_phone_number ?? string.Empty,
IsRefrigirated = x.location_refrigerated_medication,
LocationAdress = x.location_address ?? string.Empty,
LocationAreaName = x.location_general_area ?? string.Empty,
WhatsappNumber = x.location_whatsapp ?? string.Empty,
Logo = x.location_logo ?? string.Empty,
Id = x.Id,
}).ToList().ToList();
}
else
{
if (!string.IsNullOrWhiteSpace(searchTerm) && searchArea == 0)
{
locations = unitOfWork.Locations.Find(x => x.Visibility
|| x.location_name.Contains(searchTerm)
|| x.location_address.Contains(searchTerm)
|| x.location_general_area.Contains(searchTerm))
.OrderBy(x => x.Order)
.ToList();
}
if (string.IsNullOrWhiteSpace(searchTerm) && searchArea != 0)
{
locations = unitOfWork.Locations.Find(x => x.Visibility && x.location_area == searchArea).OrderBy(x => x.Order).ToList();
}
if (!string.IsNullOrWhiteSpace(searchTerm) && searchArea != 0)
{
locations = unitOfWork.Locations.Find(x => x.Visibility && x.location_area == searchArea
|| x.location_name.Contains(searchTerm)
|| x.location_address.Contains(searchTerm)
|| x.location_general_area.Contains(searchTerm))
.OrderBy(x => x.Order)
.ToList();
}
locationsVM = locations
.Select(x => new LocationVM()
{
ActivityHours = x.location_open_time ?? string.Empty,
ContactName = x.location_contact_name ?? string.Empty,
FirstPHone = x.first_phone_number ?? string.Empty,
SecondPHone = x.second_phone_number ?? string.Empty,
IsRefrigirated = x.location_refrigerated_medication,
LocationAdress = x.location_address ?? string.Empty,
LocationAreaName = x.location_general_area ?? string.Empty,
WhatsappNumber = x.location_whatsapp ?? string.Empty,
Logo = x.location_logo ?? string.Empty,
Id = x.Id,
}).ToList()
.ToList();
}
I have 2 list where I need filter data from dataBefore if not matching Name and SectionId available in dataAfter list.
var dataBefore = new List<School>
{
new School { Name = "N1", SectionId = null },
new School { Name = "N2", SectionId = new Guid("6aba7a38-8e61-472d-b4ce-b9fc2011af3f") },
new School { Name = "N3", SectionId = null },
new School { Name = "N4", SectionId = new Guid("ca663d45-04b8-4c80-96b6-c3760352a6ac") }
};
var dataAfter = new List<School>
{
new School { Name = "N1", SectionId = new Guid("5be0fc99-4826-4fbf-a190-b930af730b93") },
new School { Name = "N3", SectionId = null },
new School { Name = "N4", SectionId = null }
};
Expected output should be,
//N1 with sectionId = null
//N2 with SectionId = 6aba7a38-8e61-472d-b4ce-b9fc2011af3f
//N4 with SectionId = ca663d45-04b8-4c80-96b6-c3760352a6ac
Below query give me exact opposite result (only N3), how to get above expected result?
var x = dataBefore.Where(y => dataAfter.Any(z => z.Name == y.Name && z.SectionId == y.SectionId)).ToList();
var x = dataBefore.Where(y => !dataAfter.Any(z => z.Name == y.Name && z.SectionId == y.SectionId)).ToList();
You can get the result if the Any() returns false.
I am trying to order the following list by descending but I can't seem to figure out how it is done:
var cust = item.Profiles.Select(c => new
{
id = c.CustId,
Name = c.Name
}).ToList();
ViewBag.Customers = new MultiSelectList(cust, "id", "Name");
This is what I have already tried:
var cust = item.Profiles.Select(c => new
{
id = c.CustId,
Name = c.Name.OrderByDescending();
}).ToList();
ViewBag.Customers = new MultiSelectList(cust, "id", "Name");
This is how the list is displayed on my view:
#Html.DropDownList("id", (MultiSelectList)ViewBag.Customers, new { #class = "form-control", id = "lstCustomer" })
Note: I am trying to sort the list in alphabetical order
var cust = item.Profiles.Select(c => new
{
id = c.CustId,
Name = c.Name
}).OrderByDescending(c=>c.Name).ToList();
Or
var cust = item.Profiles.OrderByDescending(a=>a.Name).Select(c => new
{
id = c.CustId,
Name = c.Name
}).ToList();
Using Linq:
var cust = item.Profiles.Select(c => new
{
id = c.CustId,
Name = c.Name
}).OrderByDescending(c => c.Name).ToList();
Or More Elegant (Query Syntax):
var cust = (from c in item.Profiles
orderby c.Name
select new
{
id = c.CustId,
Name = c.Name
}).ToList();
To do the same thing with query syntax:
var cust = (from c in item.Profiles
orderby c.Name descending
select new
{
id = c.CustId,
Name = c.Name
}
).ToList();
suppose below query is returning City ID and City Name but if i want to pre-pend some hard coded data with linq result then how could i do it
var cityList = network.Continents
.SelectMany(continent => continent.Countries)
.Where(ctry => ctry.Id == "country")
.SelectMany(ctry => ctry.Cities,
c => new City { Id = c.Id, Name = c.Name })
.ToList();
the above query will return data this way
City ID City Name
-------- ------------
1 Bombay
2 Kolkata
3 Delhi
but i want result this way
City ID City Name
--------- -----------
0 --Select City--
1 Bombay
2 Kolkata
3 Delhi
so i want to add this data 0 as ID and --Select City-- as Name to the list which return linq query. help me with sample code. thanks
Umm... just Insert() it?
var cityList = network.Continents
.SelectMany(continent => continent.Countries)
.Where(ctry => ctry.Id == "country")
.SelectMany(ctry => ctry.Cities,
c => new City { Id = c.Id, Name = c.Name })
.ToList();
// yup, this is what I would do...
cityList.Insert(0, new City{ Id = 0, Name = "--Select City--"});
solution with Enumerable.Concat
City[] prepend = new City[] {new City { Id = 0, Name = "--Select City--"}};
IEnumerable<City> cities = network.Continents
.SelectMany(continent => continent.Countries)
.Where(ctry => ctry.Id == "country")
.SelectMany(ctry => ctry.Cities,
c => new City { Id = c.Id, Name = c.Name });
var citySequence = prepend.Concat(cities);
var cityList = citySequence.ToList();
Lets say I have a flat list of objects, each of which has a person's name, and a single Role they're in, like so:
var People = new[] {
new PersonRole(){ Name = "Adam", Role = "R1" },
new PersonRole(){ Name = "Adam", Role = "R2" },
new PersonRole(){ Name = "Adam", Role = "R3" },
new PersonRole(){ Name = "Bob", Role = "R1" },
};
Now, is there a direct way to get this into a Dictionary<string, List<string>> based on Name and Role (obviously). I did it in two steps, like below, but I have to think there's a more direct way.
Dictionary<string, List<string>> resultLookup =
People.Select(p => p.Name).Distinct().ToDictionary(str => str, str => new List<string>());
People.ForEach(p => resultLookup[p.Name].Add(p.Role));
Thanks!
Dictionary<string, List<string>> dictionary = people.GroupBy(p => p.Name).ToDictionary(g => g.Key, g => g.Select(p => p.Role).ToList());
Untested, but I think that should work...
EDIT Tested it now, and that does in fact work.
This should do it:
var people = new[] {
new { Name = "Adam", Role = "R1" },
new { Name = "Adam", Role = "R2" },
new { Name = "Adam", Role = "R3" },
new { Name = "Bob", Role = "R1" },
};
var r = from p in people
group p by p.Name
into g
select new {
Name = g.Key,
Roles = g.Select(p => p.Role).ToList()
};
var d = r.ToDictionary(k => k.Name, e => e.Roles);
var dict = People.ToLookup(p=>p.Name, p=>p.Role)
.ToDictionary(it=>it.Key, it=>it.ToList());
var result = People.GroupBy(a => a.Name).ToDictionary(a => a.First().Name, b => b.Select(c => c.Role).ToList());
People
.GroupBy( p => p.Name )
.ToDictionary( p => p.Key, p => p.Select(pr => pr.Role).ToList() )