Sunday, April 25, 2010

Get distinct

If you want to user LINQ distinct have to override IEquatable.Equals method. Rather using this it can be easily achieved like this ;

var distinctItems = items

.GroupBy(x => x.PropertyToCompare)

.Select(x => x.First());

Thursday, April 22, 2010

Update

If you want to update a field of one table from another table it can be done as follows:

Example: Table A field 2 has foreign key relationship with table B .Need to update table A field 3 with the value from table B.

Table : A
Field1 Field2 Field3
1 ------1------ Null
2 ------2------ Null

Table : B
Field1 Field2
1------- 3
2 -------4

Query 1:
UPDATE A
SET A.Field3 = B.Field2
FROM A a INNER JOIN B b ON A.Field2 = B.Field1
WHERE A.Field3 is null

Query 2:
update A
set A.Field3 = (select B.Field2 from B where B.Field1=A.Field2)
where A.Field3 is null


Query 1 is faster than Query 2