billsecond
billsecond

Reputation: 612

LINQ2SQL - FirstItem

How do you get the first item only? It seems like I have to do the following otherwise i will get an error as if it was a multiple item and i can't get just the first element of it.

My goal is i would like to remove the foreach loop from the code below.

                        MetaDataPropertyBag propertyBag = new MetaDataPropertyBag();

                        var dbResultsOfType = db.spi_GetTypesByCaseType(caseType);

                        foreach (var item in dbResultsOfType)
                        {
                            if (item.ASSOC_TYPE_ID == primaryChildTypeID)
                            {
                                propertyBag.CaseTypeDesc = item.DESCRIPTION;
                                propertyBag.Required = item.IS_REQUIRED == 'Y' ? true : false;
                                propertyBag.Parent = item.PARENT_ID.Value;
                                propertyBag.Child = item.CHILD_ID.Value;
                                propertyBag.AssocTypeID = item.ASSOC_TYPE_ID;
                                propertyBag.CaseTypeID = item.CASE_TYPE_ID;
                                break; // Only one entry is requested
                            }
                        }

Upvotes: 0

Views: 41

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

Here is one way to do it:

var first = dbResultsOfType.FirstOrDefault(item => item.ASSOC_TYPE_ID == primaryChildTypeID);
if (first != null) {
    propertyBag.CaseTypeDesc = first.DESCRIPTION;
    propertyBag.Required = first.IS_REQUIRED == 'Y' ? true : false;
    propertyBag.Parent = first.PARENT_ID.Value;
    propertyBag.Child = first.CHILD_ID.Value;
    propertyBag.AssocTypeID = first.ASSOC_TYPE_ID;
    propertyBag.CaseTypeID = first.CASE_TYPE_ID;
}

Upvotes: 1

Ashok Padmanabhan
Ashok Padmanabhan

Reputation: 2120

FirstorDefault should do it: MSDN article on firstordefault

Upvotes: 1

Related Questions