The Wayback Machine - https://web.archive.org/web/20090217132838/http://www.codeproject.com:80/script/Forums/View.aspx?fid=1004117
Click here to Skip to main content
5,896,359 members and growing! (17,549 online)
Announcements
* Bold indicates new messages since 3:28 17 Feb '09




BullFrog Power
Advanced Search
Sitemap

LINQ and .NET 3.5


Home > Forums > LINQ and .NET 3.5

 Msgs 1 to 25 of 301 (Total in Forum: 1,107) (Refresh)FirstPrevNext
QuestionNew to linq.memberDeepak Nigam1 hr 52mins ago 
Dear Friends,

m new to linq and i have searched a lot for the reference, please tell me how should i start, also i very much confused with DataContext class, i do not want to use designer for this, i want to do this by code, please provide me some reference.

thanks in advance.

Deepak Nigam
deepak@swiftcybernetics.com
http://www.swiftcybernetics.com

AnswerRe: New to linq.memberABitSmart1 hr 9mins ago 
LINQ[^]

Since you asked DataContext in a LINQ forum,
Understanding DataContext[^]

WPF DataContext[^]
QuestionConvert Inner Join to LInq???supportercode-frog17hrs 43mins ago 
I'm having a hard time grasping the Linq syntax especially with queries. I can manage the simple queries but am still getting comfortable with them but I have a join to convert to Linq and it's killing me. Here is the query:

SELECT tbl_products.ProductName, tbl_xref_product_promo_code.Price
FROM tbl_promo_codes INNER JOIN
tbl_xref_product_promo_code ON tbl_promo_codes.IDPromoCode = tbl_xref_product_promo_code.IDPromoCode INNER JOIN
tbl_products ON tbl_xref_product_promo_code.IDPrice = tbl_products.ProductID
WHERE (tbl_promo_codes.IDPromoCode = 1)



How do I recreate that in Linq? I can probably look at your code and figure it out but if you wanted to explain a few things let's start with this: (If you choose not to answer anything below totally fine. I really just need some help with the above query and that would be hugely appreciated.


from t1 in db.Table1
join t2 in db.Table2 on t1.field equals t2.field
select new { t1.field2, t2.field3}


In the from t1 since the DB doesn't contain a t1 this must be an alias right and the same for t2?

What is the select new verses just a select? Why new?



Many thanks to any who reply. I really appreciate it.
QuestionGet Hierarchical Data Using Linq2Sqlmembersrulyt0:46 15 Feb '09  
What is the best way to retrieve hierarchical data using Linq2Sql?

I have a tree of data and i want to pull it out and put it in my own classes.

The data is for a menu and I have a menu class which has children which are menu items these children in turn have children etc...

I want to pull the whole tree and place it into my own classes.

The most logical way i could think of doing this was to have an extension method that can recursively convert EntitySet<LinqMenuItem> to List<MenuItem> i would then call this

from m in DataContext.Menus where m.ID == ID select new Menu(){ Name = m.Name, ID = m.ID, Childen = m.LinqMenuItems.ToChildren()};

The ToChildren would then recursively convert all LinqMenuItems and their Children LinqMenuItems to my MenuItem implementation.

The problem with this approach is that I get an error saying ToChildren doesn't have a translation to SQL. Seemingly I cant use my own extension methods in a Linq2Sql query.

Any Ideas?
QuestionUsing linq to get data from a datatablememberMycroft Holmes17:01 14 Feb '09  
I have a standard requirement where I need to get an ID value from a datatable based on a string value from a description field. To date this is done either by a stored proc or using a filtered dataview or even a datatable.select.

I would like to get it using Linq. So far most examples seem to return a query as ienumerable of datarows so they can be bound to controls. This seems to be the default MS example. I want the int value to be returned in one statement. Is this possible without recasting the result to a datatable/row to get the value.

Never underestimate the power of human stupidity
RAH

AnswerRe: Using linq to get data from a datatablememberABitSmart0:30 15 Feb '09  
You can use First/FirstOrDefault to return a single value Smile

Example[^]
GeneralRe: Using linq to get data from a datatablememberMycroft Holmes0:40 15 Feb '09  
I'm actually after his 2nd example except I want both the select and the subsequent test for an existing record in 1 query.



iID Convert.ToInt32(data) = (from o in SupplierType
where o.Description = sDescription
select o.ID);


I will then deal with the integer iID which will be 0 or a record ID value.

Never underestimate the power of human stupidity
RAH

GeneralRe: Using linq to get data from a datatablememberABitSmart0:54 15 Feb '09  
You could you FirstOrDefault which will return null if no value is present (or you can specify a default value).

int[] numbers = { 1, 2, 3, 4, 5, 11 };
// throws an exception
int firstBigNumber = (from p in numbers where p > 10 select p).First();

// returns 0
int firstBigNumber = (from p in numbers where p > 10 select p).FirstOrDefault();

// returns 111
int firstBigNumber = (from p in numbers where p > 100 select p).DefaultIfEmpty(111).FirstOrDefault();


Example[^]

Does it serve your purpose ?
GeneralRe: Using linq to get data from a datatablememberMycroft Holmes0:59 15 Feb '09  
Thank you - I can massage the third example with no trouble at all - I really need to get a book on this stuff shortly Red faced

Never underestimate the power of human stupidity
RAH

GeneralRe: Using linq to get data from a datatablememberABitSmart1:10 15 Feb '09  
Always Welcome Thumbs Up
AnswerRe: Using linq to get data from a datatable - SolutionmemberMycroft Holmes15:43 15 Feb '09  
With thanks to ABitSmart a solution was found.

			
string sDescription = "Source system";

int iTypeID = (from t in oTable.AsEnumerable()
where t.Field("Description").ToLower() == sDescription.ToLower()
select t.Field("TypeID")).FirstOrDefault();


iTypeID has a value of 0 ot the matching ID

Never underestimate the power of human stupidity
RAH

QuestionProblems with Except methodmembergGregor838:47 13 Feb '09  
I have an XML doc that contains some file info (path, date created, etc.) and some media files in a folder with the same properties. Trying to devise some sort of way to compare the two lists and return a list of files that are not already described in the XML doc has been quite a challenge.

First I get the files and their properties from the watched folder:
Dim mediaFiles = From file In fileinfo _
Where file.Extension = ".avi" Or file.Extension = ".mov" _
Or file.Extension = ".mkv" _
Or file.Extension = ".mp4" _
Or file.Extension = ".asf" _
Select file


Then the nodes from the XML doc that describe those files:
Dim showsInXML = From s In doc...<tvshow> _
Select s


After that I compare the two lists, to get the ones that are the same:
Dim mediaOnFileSystemAndInXML = From mf In mediaFiles, sh In showsInXML _
Where mf.FullName = sh.<path>.Value _
Select mf


So far, so good. But after that when I want to 'invert' my selection (get only the files that are on disc, but not described in XML) with the following:
Dim mediaOnFileSystemAndNotInXML = mediaFiles.Except(mediaOnFileSystemAndInXML)


...I get the same ones as in the mediaFiles. As far as I can tell, I'm telling Except to compare the same objects, so what gives?
Already asked this in the VB.NET forum, but no luck. Hope you guys can help...
AnswerRe: Problems with Except methodmemberGideon Engelberth14:27 13 Feb '09  
I'm not having any problems getting the Except to work like it should. Have you verified that the mediaOnFileSystemAndInXML has the items you expect to match in it? Perhaps you have mismatched cases in the filenames.
GeneralRe: Problems with Except methodmembergGregor8322:25 13 Feb '09  
Thanks for your reply Gideon.

I *think* the problem was that I was comparing items of IEnumerable(Of System.IO.FileInfo) and IEnumerable(Of <anonymous type>, System.IO.Fileinfo), as produced by the queries for mediaFiles and mediaOnFileSystemAndInXML respectively.

Anyway, I have since found what I think is a more elegant solution (at least in terms of length of code):
    Public Sub UpdateXML()
Try
Dim doc = XDocument.Load(My.Settings.xmlMedia)
Dim newTvShows As New Collections.Generic.List(Of XElement)

Dim showPathInXML = From s In doc...<tvshow> _
Select s.<path>.Value

For Each filePath As String In My.Computer.FileSystem.GetFiles(My.Settings.mediaFolder)
Dim fileInfo As System.IO.FileInfo = My.Computer.FileSystem.GetFileInfo(filePath)
If CheckValidExtention(fileInfo.Extension) = False Then Continue For
If showPathInXML.Any(Function(f) f = fileInfo.FullName) = False Then
newTvShows.Add(<tvshow>
<path><%= fileInfo.FullName %></path>
<dateAdded><%= fileInfo.CreationTime %></dateAdded>
<seen><%= "0" %></seen>
<name><%= fileInfo.Name %></name>
<deleted><%= "0" %></deleted>
</tvshow> )
End If
Next

For Each ntvs As XElement In newTvShows
doc.<torrss>.<tvshows>(0).Add(ntvs)
Next

doc.Save(My.Settings.xmlMedia)
Catch ex As Exception
ErrorNotifyer("Error updating XML.")
End Try
End Sub


I think the lesson here for me was that LINQ is a wonderful tool to be used sparingly. Smile
QuestionGrouping with LINQmemberu2envy1221:40 12 Feb '09  
This is what I have.....

DailyHoursID
1
2
3

Table2 HoursTimeCategory
DailyHoursID TimeCategory Hours Min
1 0 8 30
1 1 9 0
2 0 6 30


How do I get a result set of the bellow using LINQ
TimeCategory Hours Min
0 14 60
1 9 0



Im getting the Hours Summed up. I just cant get the Minutes to sum up.


var rsDailyHoursTC = (from d in Empctx.DailyHoursTimeCategories
join tc in Empctx.TimeCategories on d.TimeCategoryID equals tc.TimeCategoryID
where empCatList.Contains(d.DailyHoursID)
group d.Hours by tc.TimeCategoryName into TotalArea
select new
{
Category = TotalArea.Key,
Hours = TotalArea.Sum()

});
AnswerRe: Grouping with LINQmemberABitSmart22:13 12 Feb '09  
See if this works (its not tested). I am guessing you need things grouped by the TimeCategory.

var rsDailyHoursTC = (from d in Empctx.DailyHoursTimeCategories
group d.TimeCategory into TotalArea
orderby TotalArea.TimeCategory
select new
{
TimeCategory = TotalArea.TimeCategory,
Hours = TotalArea.Sum( h => h.Hours),
Min = TotalArea.Sum( m => m.Min)
});


EDIT: Changed from DailyHoursID to TimeCategory
GeneralRe: Grouping with LINQmemberu2envy1222:31 12 Feb '09  
You missing a by clause group by

lambada Error on
TotalArea.TimeCategory,

var rsDailyMinutesTC1 = (from d in Empctx.DailyHoursTimeCategories
join tc in Empctx.TimeCategories on d.TimeCategoryID equals tc.TimeCategoryID
where empCatList.Contains(d.DailyHoursID)
group d.TimeCategory by tc.TimeCategoryName into TotalArea
select new
{
TimeCategory = TotalArea.TimeCategory,
Hours = TotalArea.Sum( h => h.Hours),
Min = TotalArea.Sum( m => m.Min)
});
GeneralRe: Grouping with LINQmemberABitSmart22:43 12 Feb '09  
u2envy12 wrote:
ambada Error on
TotalArea.TimeCategory


Is the column name TimeCategory or TimeCategoryName?

var rsDailyHoursTC = (from d in Empctx.DailyHoursTimeCategories
group d by d.TimeCategory into TotalArea
orderby TotalArea.TimeCategoryName
select new
{
TimeCategory = TotalArea.TimeCategoryName,
Hours = TotalArea.Sum( h => h.Hours),
Min = TotalArea.Sum( m => m.Min)
});

GeneralRe: Grouping with LINQmemberu2envy1223:11 12 Feb '09  
Its TimeCategoryName
Error on
orderby TotalArea."TimeCategoryName"
Does not contain a definition for TimeCategoryName
GeneralRe: Grouping with LINQmemberABitSmart23:13 12 Feb '09  
wht about the last query i gave you ??
GeneralRe: Grouping with LINQmemberu2envy1223:28 12 Feb '09  
Get an error on
orderby TotalArea.TimeCategoryName
If I remove orderby

Get an error on
TimeCategory = TotalArea.TimeCategoryName,

var rsDailyHoursTC1 = (from d in Empctx.DailyHoursTimeCategories
join tc in Empctx.TimeCategories on d.TimeCategoryID equals tc.TimeCategoryID
where empCatList.Contains(d.DailyHoursID)
group d by tc.TimeCategoryName into TotalArea
orderby TotalArea.TimeCategoryName
select new
{
TimeCategory = TotalArea.TimeCategoryName,
Hours = TotalArea.Sum(h => h.Hours),
Min = TotalArea.Sum(m => m.Minutes)
});
GeneralRe: Grouping with LINQmemberABitSmart23:42 12 Feb '09  
u2envy12 wrote:
DailyHoursID
1
2
3

Table2 HoursTimeCategory
DailyHoursID TimeCategory Hours Min
1 0 8 30
1 1 9 0
2 0 6 30


I wrote the query based on the data you provided. The query you have posted and data(tablename, column name) do not match at all.
GeneralRe: Grouping with LINQmemberu2envy120:05 13 Feb '09  
Sorry..... Let me get the names correct.

DailyHoursID
1
2
3

Table2 HoursTimeCategory
DailyHoursID TimeCategoryID Hours Min
1 0 8 30
1 1 9 0
2 0 6 30


Table3 TimeCategory
TimeCategoryID TimeCategoryName
1 Normal Time
2 Over Time

Join on Table3 to get the TimeCategoryName
AnswerRe: Grouping with LINQmemberJon Rista14:50 13 Feb '09  
You are trying to group and join at the same time, which is actually quite problematic in LINQ. Instead, join and select the fields you need into a new result set, then group that result set. Like so:


var rsDailyHoursTC =
from rs in
(
from d in Empctx.DailyHoursTimeCategories
join tc in Empctx.TimeCategories on d.TimeCategoryID equals tc.TimeCategoryID
where empCatList.Contains(d.DailyHoursID)
select new { TimeCategoryName = tc.TimeCategoryName, Hours = d.Hours, Minutes = d.Min }
)
group rs by rs.TimeCategoryName into g
select new { Category = g.Key, Hours = g.Sum(r => r.Hours), Minutes = g.Sum(r => r.Minutes) };

Questionwhat is LINQmemberJAS GIRI19:59 12 Feb '09  
introduction and suitable example

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   


Last Updated 9 Aug 2007
Web16 | Advertise | Privacy
Copyright © CodeProject, 1999-2009
All Rights Reserved. Terms of Use