.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

LINQ select distinct

Posted By:      Posted Date: September 27, 2010    Points: 0   Category :ASP.Net


I have a select like this one:

var x = from t in dc.table
where t.sourceId = 5
order by t.itemId descending
select new { t.itemId, t.sourceId, t.title }

I would select only the records with a unique title and let the other fields like sourceId to have duplicates. How can I do this please ?

View Complete Post

More Related Resource Links

Select Distinct Using Linq

We have a list and when want to filter the list based on property to get the unique List.

Please help me to find out distinct value from linq to sql query given.

profileuserDataContext db = new profileuserDataContext(); var Q = (from p in db.edufinals join RM in db.edufinals on p.UserName equals RM.UserName where p.name.StartsWith(srcval) select new { p.name, RM.ProfielID, RM.ProfielPic, RM.city }).OrderBy(x => x.name).Distinct().Take(10);//, p.Key.ProfielID, p.Key.ProfielPic, p.Key.city, p.Key.country foreach (var pg in Q.Distinct()) { Response.Write(pg.name); ..................................... .................................... } how to refine this query to get distinct "name" column? Please help me to find out exact value.

Use of PATINDEX function in select clause With Linq

hello       i have an problem to use of PATINDEX function in select clause with Linq.      if anyone have any clue about it then please update me its urgent.Thanks In Advance.

Insert a "Select User" row in Linq for a dropdown list

I'm new to Linq. I have searched and searched the web for a soluion, and can't find anything. I have a Linq query and I want to insert a row ("Select User") to the top before I pass it to the drop down list. I've been trying to use the Union but to now avail (it keeps telling me that my object doesn't support the Union method). My code, prior to attempting to inser a row, is very simple.public SelectList DropDown_Users()        {            var context = new VivarianDataContext();            var query = from t in context.AspnetUsers                        select new { t.UserId, t.LastName };            list = new SelectList(query.AsEnumerable(), "UserId", "LastName");            return list;        }Now I try to insert a row and I found this on the internet and it seems to say that his solution will work. But it is filled with syntax errors. http://magicode.wordpress.com/2009/08/20/inserting-an-item-in-iqueryable-object-using-union-met

Linq Distinct

Hi, I'm not sure if this is the right forum to ask. But I'm using ASP.net 3.5 & I've below code:string[3] arrSerialKey = {"abcd", "45pr", "ty66"}; var arrDistinctSerialKeys = arrSerialKey.Distinct(); Now, I want to check how many elements are present in this distinct array & if the number of elements in this distinct array is more than 500, then I need to fetch only those first 500 elements. How can I acheive this? Thanks! 

select distinct best row based on a condition

Hi all . The application I'm working on only allowed that one user had one usergroup. I create a User_UserGroup table to allow a user to have n usergroups. My problem now is the following: User 'ablanco' belongs to UserGroup 'comercial' and 'financeira' If i execute this commands i get the following results: SELECT * FROM [T_APP_ModulePermition] WHERE [UserGroup] = 'comercial' http://img26.imageshack.us/i/49234843.png ----------------------------------------------------------------------------------- SELECT * FROM [T_APP_ModulePermition] WHERE [UserGroup] = 'financeira' http://img259.imageshack.us/i/32526938.png ----------------------------------------------------------------------------------- I now need to get distinct rows that belong to ablanco's Usergroups but if on one group the module is Enable=0 and on the other the same module is Enable=1 it should return the ont that has Enable = 1 The attempt i made without taking in consideration this 'Enable' part was the following: SELECT MP.* FROM [T_APP_ModulePermition] MP     INNER JOIN T_APP_UserGroup_Detail UGD ON MP.UserGroup=UGD.UserGroup     INNER JOIN T_APP_User U ON UGD.UserId = U.UserId WHERE U.UserId='ablanco' But since i cant use DISTINCT.* i get all the 14 rows. If someone can help me on this i would be thankful.

Get Distinct value from a Group-Join syntax Linq

Hello,I have this group-join syntax but I couldn't get the distinct value from the relational tables below.Table_1key_1 t1_value1     Food2     Sports3     Leisure 4     Trip5     ZooTable_2key_2   key_1  t2_boolean15        1          True16        1          True17        1          True18        2          True19        2          True20        2          Falsedesire result:FoodSports            Dim c = (From t1 In dbContext_Table_1 _                                     Group Join GroupTable In _db.Table_2 On GroupTable.key_1 Equals t1.key_1 Into Group 

Avoiding a SELECT distinct query generated by SSAS when using dimension derived from fact table

Hi, I am using a dimension derived out ot a fact table and the factt able primary key is dimension key. Issue is, there are large number of rows and so many attributes. SSAS issues distinct query and it takes large amount of time. Without the distinct statement, query takes only 3 min for 4 million rows. With the distinct, it takes 20 min. Becuase the fact primary key is the dimension key there is no need of a distinct statement. I know there is a option in the dimension to say "By Table" to avoid this. But unfortuantely, i breach the 4 GB limit for strings. Any suggestions for optimization? Thanks,  Sambath

LINQ. select query with OR.

Executing 'SELECT' query with 'WHERE' clause which have 'OR' and 'AND' operators give wrong result. Example: Have 4 tables: table1,table21,table22,table3. Relations between it: 'table1' OneToMany 'table21' and 'table22',  'table3' OneToMany 'table21' and 'table22'. tables 'table21' and 'table22' store relations between 'table1' and 'table3'. Example query { from t1 in table1 from t21 in table21 from t22 in table22 from t3 in table3 where (t1.ID==t21.t1ID & t21.t3ID==t3.ID) | (t1.ID==t22.t1ID & t22.t3ID==t3.ID) select t3; } give huge amount duplicate results Although similar query { ( from t1 in table1 from t21 in table21 from t3 in table3 where (t1.ID==t21.t1ID & t21.t3ID==t3.ID) select t3 ).Union( from t1 in table1 from t22 in table22 from t3 in table3 where (t1.ID==t22.t1ID & t22.t3ID==t3.ID) select t3) } give right result (much less duplicate results). In spite of we can filter result with 'DISTINCT' operator - difference in performance between two examples is enormous.

ORDER BY items must appear in the select list if SELECT DISTINCT is specified


Hi, i am using a query to get DISTINCT hotels from my Database table sorted by Price and it returns me same hotel times of record found by Price if i use this Query

SELECT distinct(hotelname), availstatus, hoteladdress, hotelphonenumber, hotelpostalcode, destination, starrating, imageurl, hotelcode, TempSession, HotelType, MinimumNightRate from HproTemp where TempSession = '12-53-37' ORDER BY MinimumNightRate

and i get the error "ORDER BY items must appear in the select list if SELECT DISTINCT is specified" When i remove MinimumNightRate from SELECT LIST.

Can anyone have any idea how may i resolve it..

Linq to entities: Always select before delete and update?



With linq to entities, how can I delete and update data inside a database without first selecting the complete entity at first?
The idea behind this is to improve performance.


How to do "Select top 1 customer from customers" in Linq to Sql?


I've gotten half way there:

 var customerList = from c in dc.Customers orderBy c.Sales select c;

 That gets me a collection of customers. How do I use the equivalent of the top operator in SQL?



ORDER BY items must appear in the select list if SELECT DISTINCT is specified


why am i getting the error message when both ORDER BY items appear in the SELECT query?



	CONVERT(VARCHAR(8),BI.DateFrom ,3) as FFromDate,
	CONVERT(VARCHAR(8),B.CreatedDate ,3) as FBookingDate,
	CAST(FLOOR( CAST( B.CreatedDate AS FLOAT ) ) AS DATETIME) as BookingDate,
	(C.Forename + CASE 

Select Distinct Problem.



I have a user defined data table like this.





/****** Object:  UserDefinedTableType [dbo].[udtt_AssemblyItem]    Script Date: 10/05/2010 11:47:57 ******/

CREATE TYPE [dbo].[udtt_AssemblyItem] AS TABLE(

[Id] [int] NOT NULL,

[SystemTypeDescription] [varchar](100) NOT NULL,

[Type] [varchar](100) NOT NULL,

[SubType] [varchar](100) NOT NULL,

[Depth] [decimal](18, 3) NOT NULL,

[Height] [decimal](18, 3) NOT NULL,

[Width] [decimal](18, 3) NOT NULL,

[MaterialCost] [decimal](18, 3) NOT NULL



Now I add some records to it like this.
declare @p1 dbo.udtt_AssemblyItem
insert into @p1 values(0,'SL 1000','Partition','',1.800,1.800,0.300,402.560)
insert into @p1 values(0,'SL 1000','Nib','150mm',0,1.800,0.150,70.840)
insert into @p1 values(0,'SL1010','Partition','',1.500,1.800,0.300,197.810)
insert into @p1 values(0,'SL1010','Nib','150mm',0,1.800,0.150,55.180)
insert into @p1 values(0,'CL 1000','Partition','',1.500,1.800,0.300,368.090)
insert into @p1 values(0,'CL 1000','Nib','150mm',0,1.800,0.150,70.840)
insert into @p1 values(0,'CB 2000','Partition','',1.500,1.800,0.

Linq select null value

from e in Employees
where e.EmployeeID == id
select new {
Sales1 = e.HomeSales.Max(),
Sales2 = e.AwaySales.Max()};

I have to get the maximum of these two select values. The select values are nullable. How do I go about checking if the value is null before
calling the Max() method on it?

I tried the ?? coalesing operator (example: e.HomeSales.Max() ?? 0M,) but I get the following error:

"Operator '??' cannot be applied to operands of type 'decimal' and 'decimal'"

select query for linq on Default.aspx.cs page


how do i create linq query and asign that query to as data source to datalist on default.aspx.cs page

select certian records linq to sql


I have a database with a GUID and images,

one function

I want to get the first record (if exists) and return results


 second function

i want to get the second record only if a second record exists


I guess I have to return the records frmo the table then just movenext so to speak in a loop to select the second record but guessing there is a better faster way to do that in linq

I see some example for .take(1)  I assume that will always take the first record and return nothing else. I dont need this to be random. and what happens if there are no records return?

for the second function

I gues its  .skip(1).take(1)   will that for sure skip the first record and return the  second one to my var? again what if thier is no second record i would not want any results return if this is not the case (no scond record then want nothing back and no error)



ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend