Using Linq Retrieveing the data to SelectListItem - linq

I have class studentList
public class studentList
{
public static IEnumerable<SelectListItem> GetStudents(int? ID)
{
//code is required here
return ;
}
}
Iam getting ID into this method and now, I require all other IDs from the table, excluding the passed parameter ID using linq.
I have Student table which contains Two fieds StudentID and StudentName,
Now I require IDs and Names of the students in the above pattern..
Could any one help me...

Might like to read : SQL to LINQ ( Visual Representation )
var data= form s in Students
where s.StudentID != ID
select new {ID= s.StudenID,Name = s.StudentName};
image presentaion might be like

Related

How to select column in web api using LINQ

I'm really a newbie in ASP.NET, I have a table consists of 4 columns, id, name, address, and phone. I'd like to do a query select id, name from table x but I have no idea how to write it using LINQ in ASP.NET web API
public class rateperjamallController : ApiController
{
public double GET()
{
TeamDataContext db1 = new TeamDataContext();
var item = db1.Teams.Select(c => c);
var id = item.Select(a => a.id);
return id;}
}
}
Does anyone have any idea to help me since I am really a newbie?
Are you looking fora specific record in the dataset? If yes, you need to pass the id or name and create a query for that. For example, this is what you can do: (if you pass id as a parameter)
public class rateperjamallController : ApiController
{
public double GET(string id)
{
TeamDataContext db1 = new TeamDataContext();
return db1.Teams.Where(x => x.id == id)?.First();
}
}

Realm Xamarin LINQ Object

What is the correct way to query Realm with LINQ where the query includes fields from other Realm objects? For example:
public class Department : RealmObject
{
[Primary Key]
public string UniqueId { get; set; }
}
public class Employee : RealmObject
{
[Primary Key]
public string Name { get; set; }
// Parent
public Department Department { get; set; }
}
Then I would expect to be able to do something like:
var employee = realm.All<Employee>().SingleOrDefault( e => e.Department.UniqueId == fooId && e.Name == fooName );
But this always returns no matches. Where() also returns no matches. However, eliminating the e.Department and searching only on employee name works fine but obviously does not scope to Department as intended.
This is with the latest Realm Xamarin 0.80.
What am I doing wrong?
Querying by nested RealmObjects attributes is not currently supported:
Just to clarify here, we don't yet support queries on related objects like this. We will in the future, but there is no timeline at the moment.
The following is also not currently supported:
var deptFilter = theRealm.ObjectForPrimaryKey<Department>("HR");
var employeesByDept = theRealm.All<Employee>().Where((Employee emp) => emp.Department == deptFilter & emp.Name == "StackOverflow");
The left-hand side of the And operator must be a direct access to a persisted property in Realm.
Unable to process '(emp.Department == value(Realm080.App+c__AnonStorey1).deptFilter)'.
You can do direct RealmObject equalities, just not in the same Linq expression, so break it down further into a sub-query.
Example of how I currently do it:
var deptFilter = theRealm.ObjectForPrimaryKey<Department>("HR");
var employeesByDept = theRealm.All<Employee>().Where((Employee emp) => emp.Department == deptFilter);
var employees = employeesByDept.Where((Employee emp) => emp.Name == "StackOverflow");
foreach (var emp in employees)
{
D.WriteLine(emp.Name);
}
Note: https://github.com/realm/realm-dotnet/issues/723

What does this LINQ do?

I am trying to learn LINQ query expressions. In MS website, I found this LINQ query.
public void Linq16()
{
List<Customer> customers = GetCustomerList();
var orders =
from c in customers
from o in c.Orders
where o.OrderDate >= new DateTime(1998, 1, 1)
select new { c.CustomerID, o.OrderID, o.OrderDate };
ObjectDumper.Write(orders);
}
I am not sure what that c.Orders does. I visualized customers and orders like data tables. Can someone tell me what this c.Orders does and what is it called?
It means that the entity Customer has a related entity, namely Order. The table might look like:
Order
OrderID
OrderData
CustomerID (this is a Foreign Key to the Customer table)
Customer
CustomerID
Name
...
The Entity Framework will recognize the relationship between the two tables and create classes, similar to following:
public class Customer
{
public int CustomerID { get; set; }
public virtual ICollection<Order> Orders { get; set; }
}
public class Order
{
public int OrderID { get; set; }
public DateTime OrderDate { get; set;}
public int CustomerID { get; set; }
public virtual Customer Customer { get; set; }
}
To understand the code a little more, the double from could be rewritten as:
foreach(Customer c in customers)
{
foreach(Order o in c.Orders)
{
if(o.OrderDate >= new DateTime(1998, 1, 1))
{
yield return new { c.CustomerID, o.OrderID, o.OrderDate };
}
}
}
This is NOT LINQ, but LINQ to entities.
Its a related entity. Basically its another table, and you can use it through including it.
When doing it with sql, you would have to select the table by the foreign key, EF does that automatically for you.
What you're doing there is the same as Include: MSDN blog example.
Include() is the Method syntax of the part of the query you dont understand.
Entity Framework creates a list of items of the other table as member of your entity - which is weird in the first place (just unusual actually) but very very useful, since you can ToList() the entity and they will be included if you .Include() them before.
To be very exact, you have a List (or something similar to list) added to the customer object (this is done by entity framework) and every Order is a line in the Orders table.
If you do want to use linq, but not Entity Framework, ignore it and search for other sources to learn linq.
Here is a really good resource to learn: MSDN, 101 LINQ examples

mvc3 best way to convert anonymous type to an ienumerable

I have a model that uses an IEnumerable to return multiple rows using a foreach statement in the view. The issue is that I am using a Join because I need data from 2 different tables which turns the ienumerable into an anonymous type and is causing errors; whats the best way I can fix this?
var Ieposts = (from t in db.Threadposts join p in db.profiles on t.profileID equals p.profileID where t.threadID == id select new
{
firstname = p.firstname,
lastname = p.lastname,
articles = p.articlecount,
city = p.city,
state = p.state,
post = t.post
}).ToList();
I am only getting out the fields that I need because that increases database performance. Any suggestions would be great
I think you really need to learn a bit more about Entity Framework and Linq in general.
Joins do not create anonymous types, nor is there any problem with getting an enumerable from an anonymous type. Just call .AsEnumerable() from the query.
However, I suspect this is not what you're trying to do. What you actually want is a concrete return type. In That case, you probably want to create a type for this:
public class IEPost {
public string FirstName {get;set;}
public string LastName {get;set;}
public int Articles {get;set;}
public string City {get;set;}
public string State {get;set:}
public Post Post {get;set;}
}
Then you create your query like so (note the "new IEPost" part):
var Ieposts = (from t in db.Threadposts
join p in db.profiles on t.profileID equals p.profileID
where t.threadID == id select new IEPost
{
FirstName = p.firstname,
LastName = p.lastname,
Articles = p.articlecount,
City = p.city,
State = p.state,
Post = t.post
}).ToList();

How can I pass any id to a linq join in [HttpGet] ActionResult for Edit

I am making a web application on MVC3, and I am using linq to communicate with the database.
I made a checkboxlist, where a user can select some options according to their choice and it gets saved in the databse table. The problem is in the Edit part.
The whole scenario is something like this:
The user can register as a restaurant owner or a Motel owner, I have assigned different Business_Type_Id as 1 and 2 for differentiating these two, I have assigned '2' for the Restaurant Business Type, and mapped the cuisines with the perticular business type in the same "Cuisines" table, by adding the "BusinessType" column into the table. the user will be assigned a Business_Id for their Business. I am providing a checkboxlist which generates its options from the database table "Cuisines" where I have given the cuisine list. From the front end the user can choose multiple cuisines according to their chioce what ever they provide in their restaurant. The choices may vary from one restaurant owner to the other, so I am storing the selected values for each and every Restaurant owner in a "BusinessCuisinesMapping" table, where I map the perticular BusinessId with the selected CuisineId by that perticular user.
Now to populate that cuisine list for edit or update I wrote a linq join, but I need to compare it with the Business_Id which is passed to the [HttpGet] ActionResult Edit. And this is point where I got stuck.
This is my linq join code which I am using in the controller:
[HttpGet]
public ActionResult Edit(int id)
{
using (var chkl = new BusinessEntities())
{
var data = (from CuisinesData in chkl.Cuisines
join BusinessCuisineMappingData in chkl.BusinessCuisineMapping
on new { CuisinesData.Id, id } equals new { BusinessCuisineMappingData.CuisinesId, BusinessCuisineMappingData.BusinessId }
where CuisinesData.BusinessTypeId == 2
select new CusinesDTO
{
Id = CuisinesData.Id,
Name = CuisinesData.Name,
IsSelected = BusinessCuisineMappingData.CuisinesId == null ? false : true
}).Distinct().ToList();
ViewBag.CuisineList = data;
}
return View();
}
This is my DTO class:
public class CusinesDTO
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsSelected { get; set; }
}
I want to comape the "id" with the "BusinessCuisineMappingData.BusinessId" field in my LINQ join, which I am getting through the [HttpGet] Actionresult Edit(int id). It prompts me an error while I try to implement it.
You cannot use a local variable in the join. However, you can use it in a Where clause. So if you do
join ...
on CuisinesData.Id equals BusinessCuisineMappingData.CuisinesId
...
where BusinessCuisineMappingData.BusinessId == id
you'll have the same effect.
"The type of the expressions in join clause is incorrect. Type inference failed in the call to 'Join'"
This suggests the types on either side of your JOIN are not equal. You are getting a compiler error; should be relatively easy to check the types on either side of your JOIN clause.
edit: rereading what you have put, I think something like the below is what you want to do:
[HttpGet]
public ActionResult Edit(int id)
{
using (var chkl = new BusinessEntities())
{
var data = (from CuisinesData in chkl.Cuisines
join BusinessCuisineMappingData in chkl.BusinessCuisineMapping
on CuisinesData.Id equals BusinessCuisineMappingData.CuisinesId
where CuisinesData.BusinessTypeId == id
select new CusinesDTO
{
Id = CuisinesData.Id,
Name = CuisinesData.Name,
IsSelected = BusinessCuisineMappingData.CuisinesId == null ? false : true
}).Distinct().ToList();
ViewBag.CuisineList = data;
}
return View();
}

Resources