Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to select data from one table not in other table

Hi i have the following code to select data from one table not in other table

var result1 = (from e in db.Users
               select e).ToList();
var result2 = (from e in db.Fi
               select e).ToList();
List<string> listString = (from e in result1
                           where !(from m in result2
                                   select m.UserID).Contains(e.UserID)
                           select e.UserName).ToList();

ViewBag.ddlUserId = listString;

Am getting value inside listString .But got error while adding listString to viewbag.

Unable to cast object of type 'System.Collections.Generic.List`1[System.String]' to type 'System.Collections.Generic.IEnumerable`1[Main.Models.Admin.User]'.
like image 384
Mizbella Avatar asked Apr 27 '13 04:04

Mizbella


People also ask

How do you select all records from one table that do not exist in another table LINQ?

Users select e). ToList(); var result2 = (from e in db.Fi select e). ToList(); List<string> listString = (from e in result1 where !( from m in result2 select m.

Is LINQ faster than SQL?

More importantly: when it comes to querying databases, LINQ is in most cases a significantly more productive querying language than SQL. Compared to SQL, LINQ is simpler, tidier, and higher-level.

Can LINQ query work with Array?

Yes it supports General Arrays, Generic Lists, XML, Databases and even flat files. The beauty of LINQ is uniformity.

What is difference between select and where in LINQ?

Select will always return the same number of elements in the list (regardless of a filter condition you may have). Where can return less elements depending on your filter condition.


Video Answer


2 Answers

var res = db.tbl_Ware.where(a => a.tbl_Buy.Where(c => c.tbl_Ware.Title.Contains(mtrTxtWareTitle.Text)).Select(b => b.Ware_ID).Contains(a.ID));

This mean in T-SQL is:

SELECT * FROM tbl_Ware WHERE id IN (SELECT ware_ID, tbl_Buy WHErE tbl_Ware.title LIKE '% mtrTxtwareTitle.Text %')
like image 33
sali Avatar answered Oct 24 '22 23:10

sali


Try this it is very simple.

var result=(from e in db.Users
            select e.UserID).Except(from m in db.Fi
                                    select m.UserID).ToList();
like image 76
Pranav Avatar answered Oct 25 '22 00:10

Pranav