Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x

LINQ Query

526

Solutions

388

Contributors

Language Integrated Query (LINQ) is a Microsoft .NET Framework component that adds native data querying capabilities to .NET languages, although ports exist for Java, PHP, JavaScript and ActionScript. LINQ extends the language by the addition of query expressions, which are akin to SQL statements, and can be used to conveniently extract and process data from arrays, enumerable classes, XML documents, relational databases, and third-party data sources.

Share tech news, updates, or what's on your mind.

Sign up to Post

I have xml below, and If i just give you  'applicantFirstName' and the value is 'John'
how can we add
'John' into       <FirstName ID="applicantFirstName" PrefillValue="No">John</FirstName>?

based on two requirements

1. I will only pass you  Dictionary<string, string> e.g. <applicantFirstName,'john'>
2. You actually do not know the structure of xml except you know each element has "ID" attritbute. meaning that you pass 'applicantFfirstName'' only into xml, and try to find element, and add value (John) there.

so you won't be able to use linq like doc.Descendants("Applicant").FirstOrDefault()

Let me know if this is possible.

<Surety>
  <SuretyLine>
    <Commercial>
      <Bond>
        <GeneralInformation UI="BondInfo">
          <Name ID="bondName" PrefillValue="Yes">Contractor</Name>
          <State ID="bondState" PrefillValue="Yes">CA</State>
          
          <Code PrefillValue="Yes">888</Code>
          <Renew PrefillValue="Yes">
            <Year>1</Year>
          </Renew>
        </GeneralInformation>
        <Coverage>
          <Amount PrefillValue="Yes">15000</Amount>
          <Year PrefillValue="Yes">1</Year>
        </Coverage>
        <Applicant>
          <CompanyName ID="applicantCompanyName" PrefillValue="No"></CompanyName>
          <CompanyEntityType ID="applicantCompanyEntityType" PrefillValue="No"></CompanyEntityType>
          <CompanyTaxID ID="applicantCompanyTaxID"></CompanyTaxID>
          <FirstName 

Open in new window

0
Tech or Treat! - Giveaway
LVL 10
Tech or Treat! - Giveaway

Submit an article about your scariest tech experience—and the solution—and you’ll be automatically entered to win one of 4 fantastic tech gadgets.

get alert on line if (elementID == update.Key) because update.key is string.
how can i fix it?

       
 public void CreateQuoteFile(Dictionary<string, string> changes)
        {
            string fileName = CreateXmlfile("License","CA");
            XDocument doc = XDocument.Load(fileCreateQuotePath+fileName);
            foreach (var update in changes)
            {
                var element = doc.Descendants(update.Key).FirstOrDefault(); //element from XML file
                var elementID = doc.Descendants(update.Key).Select(b=>b.Attribute("ID")).FirstOrDefault(); //element ID from XML file

                //if (elementID != null) 
                if (elementID == update.Key)
                {
                    element.Value = update.Value;
                }
            }
            string fileNameNew = Guid.NewGuid().ToString() + ".xml";
            doc.Save(fileCreateQuotePath + fileNameNew)

Open in new window

;
0
Below codes is reading my xml Applicant
and try to find Element e.g. CompanyName (var element = doc.Descendants(update.Key).FirstOrDefault();)
But I try to find ID, how can i do that?
My goal is to find ID
like applicantCompanyName = update.value


public void CreateQuoteFile(Dictionary<string, string> changes)
        {
            string fileName = CreateXmlfile("CA");
            XDocument doc = XDocument.Load(fileCreateQuotePath+fileName);
            foreach (var update in changes)
            {
                var element = doc.Descendants(update.Key).FirstOrDefault();
                if (element != null)
                {
                    element.Value = update.Value;
                }
            }

            string fileNameNew = Guid.NewGuid().ToString() + ".xml";
            doc.Save(fileCreateQuotePath + fileNameNew);            
        }



<Applicant>
<CompanyName PrefillValue="No" ID="applicantCompanyName"/>
<CompanyEntityType PrefillValue="No" ID="applicantCompanyEntityType"/>
<CompanyTaxID ID="applicantCompanyTaxID"/>
<FirstName PrefillValue="No" ID="applicantFirstName">asdfasdf</FirstName>
<LastName PrefillValue="No" ID="applicantLastName"/>
<MiddleName PrefillValue="No" ID="applicantMiddleName"/>
<StreetName PrefillValue="No" ID="applicantStreetName"/>
<City PrefillValue="No" ID="applicantCity"/>
<State PrefillValue="No" ID="applicantState"/>
<Zip PrefillValue="No" ID="applicantZip"/>
<PhoneNo PrefillValue="No" …
0
1. How can get the list (element (State)))  filter by state if parameter is given e.g. (CA) order by State asc?
2. How can get the list (element (Name)) filter by Status = Online and state = "CA" order by Name asc?

3. How can get total count of Bond filer by state?
4. How can get total count of Bond filter by Status (e.g. Online)?

I would like to see in c#.

Thanks,


<Surety>
<SuretyLine>
<Commercial>
<Bond>
        <GeneralInformation UI="BondInfo">
          <Name ID="bondName" PrefillValue="Yes">C</Name>
          <State ID="bondState" PrefillValue="Yes">CA</State>         
        </GeneralInformation>              
        <Status>Online</Status>
</Bond>
<Bond>
        <GeneralInformation UI="BondInfo">
          <Name ID="bondName" PrefillValue="Yes">Z</Name>
          <State ID="bondState" PrefillValue="Yes">CA</State>         
        </GeneralInformation>              
        <Status>Online</Status>
</Bond>
<Bond>
        <GeneralInformation UI="BondInfo">
          <Name ID="bondName" PrefillValue="Yes">B</Name>
          <State ID="bondState" PrefillValue="Yes">FL</State>         
        </GeneralInformation>              
        <Status>Online</Status>
</Bond>
</Commercial>
</SuretyLine>
</Surety>

Open in new window

0
Hi Experts,

I have tried to round off a value x = 455.77 using math .round() function but not rounded the value 466.

Code I have given to round off:

var rounded = Math.Round(x, 2, MidpointRounding.AwayFromZero);

Open in new window


Could you guys please explain whats wrong here?

Thanks,
Anjala Baby
0
I trying to read the attached jSon response. Also attached is the class that I am using. Below is the code to load the response in a collection so I can populate a datagrid.

Dim docs2 = JArray.FromObject(parsedObject("enrollments")).Select(Function(x) x.ToObject(Of jSonClass.enrollments)())
            Dim empList As New System.Collections.Generic.List(Of jSonClass.enrollments)
            empList = docs2.Select(Function(x) x).ToList

I am getting the error on the last line. "Object reference not set to instance of an object.
jSonClass_EE.txt
EE_jSon_Enrollments.txt
0
0
Hi

I have this section of code, using LINQ to get the data from an EF back end.

How would I change it to order by School.Name? I have tried several approaches and getting nowhere.

var school = _unitOfWork.school.Find(x => x.Specialty != null && x.Specialty.Id == specialtyId).ToList();
                var schoolDTOs = _schoolMapper.Map(school);
                return schoolDTOs;

Andy
0
I need help to create the LINQ query for EF. it is easy in T-sql, not that easy in LINQ.
Here is the data structure:
Group contains multiple tags. (Tag: tagId, groupId, tagName)
Group contains memberships. (Membership: membershipId, groupId, userPin)
Memberships need to link Person to get the DisplayName.  (person: PersonId, userPin, DisplayName)
So getAll():
return _db.Groups
.include(x => x.Tags)
.include(x => x.Memberships)
.include(x => x.memberships.Select(y => y.Person));

Now I want it returns only those groups whose memberships contains userPin=1234. In other words, given user pin=1234, find all the groups that user joins.

In T-sql:
select g.*, t.*, m.*, p.*
from Group g
inner join Tags t on g.groupId = t.groupId
inner join membership m on g.groupId = m.groupId
inner join person p on m.userPin= p.userPin
where m.userPin= 1234

How do I accomplish that in LINQ (method syntax)? Your help will be greatly appreciated. Thanks
0
Hi,
I need to create a report in SharePoint 2013 , on premises , There is a custom SharePoint list which has username, Manager and Status. say it SPLIst
I have created another SharePoint list as external content type using SQL procedure which returns all all active users. In this second list say DBList I have username and their department.
My requirement is , I need to compare the two lists and whoever is not found in SPList, should be marked as "Not Started".

Could you please help me to achieve this?

Thanks in advance.
Azra
0
Keep up with what's happening at Experts Exchange!
LVL 10
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Hi,

How to write LINQ query to split and find the column min and maximum and return based on string values.

I done some code using LINQ, but it is not working.

what is the problem in my code.

Scenario is,

1. Split the string and find the column

2. Check the minimum and maximum range of each splitted string. (SUB C=100#SUB D=200)

3 range should check within the limit like 100 min and max

Hi,

How to write LINQ query to split and find the column min and maximum and return based on string values.

I done some code using LINQ, but it is not working.

what is the problem in my code.



 protected void Button_Click(object sender, EventArgs e)
    {

        
        string string1 = "SUB C=100#SUB D=200";

        string FinalOutput = "GRADE#SUB B";

        DataTable dt = new DataTable();
        dt.Columns.AddRange(new[] { new DataColumn("Studentno"),new DataColumn("GRADE"),new DataColumn("SUB B"), new DataColumn("SUB C(MIN)"), new DataColumn("SUB C(MAX)"),
new DataColumn("SUB D(MIN)") ,new DataColumn("SUB D(MAX)") ,new DataColumn("SUB C"),new DataColumn("FROM"),new DataColumn("TO") });
        dt.Rows.Add(101,"A", "100", "100", "200", "200", "300", null, 20, "100");
        dt.Rows.Add(101, "B", "100", "150", "250", "250", "350", null, 20, "100");
        dt.Rows.Add(101, "B", "100", "200", "300", "100", null, null, 20, "100");
        dt.Rows.Add(101, null, "100", "200", "300", "100", null, null, 20, "100");



        //Check whether a given 

Open in new window

0
I have a collection of elements. Each element is identified by a string key composed of 6 string subkeys labeled A,B,C,D,E,F.

The full key is produced by concatenating together the 6 string subkeys and inserting a delimiter between each subkey. Say '.' is the delimiter character.

So a key might be "12.34.56.78.90.10"
and the subkeys are:
A=12
B=34
C=56
D=78
E=90
F=10

A subkey string may also be empty.
e.g.
A key might be "12.34.56.78"
and the subkeys are:
A=12
B=34
C=56
D=78
E=""
F=""

I wish to find a "best match" given specific values for A,B,C,D,E,F, where some of those values may be the empty string.

A "best match" is determined by the following:
For example, given A,B,C,D

  a. Look for an exact match to {A,B,C,D,-,-}
  b. Look for an exact match to {A,B,C,D,*,-}
  c. Look for an exact match to {A,B,C,D,*,*}
  d. Look for an exact match to {A,B,C,-,-,-}
  e. Look for an exact match to {A,B,-,-,-,-}
  f. Look for an exact match to {A,-,-,-,-,-}
  g. Give up.

- means the empty string ""
* means we'll accept anything that's not an empty string.

The general idea is if we don't have an exact match, then we first look deeper for a match, and if nothing is found, then we look shallower for a match, until we find a match or exhaust our options.

A few caveats:

If A=5 then do the above but ignore values B & C (accept anything including -)
If A=6 then do the above but ignore value C (accept anything including -)
If A=4 and D is …
0
I have been tasked with adding some very specific searching behaviour to a MVC application using Entity Framework.  

The searching should be able to get:

Entries with two or more words that are not just exactly next to each other. If they type in "The Revenge":
  • The Revenge
  • The Horrible Revenge
  • Revenge of the Machines

Parts of words. If they type in "Smith":
  • Mr and Mrs Smith
  • Meet the Smithsons
  • The Incredible Blacksmith

I have written the following method in my controller class:

public ActionResult Index(string searchString)
        {

            var films = from s in db.films
                        select s;

            if (!string.IsNullOrEmpty(searchString) && !searchString.Any(x => Char.IsWhiteSpace(x)))
            {
                searchString.Trim();
                films = films.Where(s => s.title.Contains(searchString)
                    || s.title.StartsWith(searchString)
                    || s.title.EndsWith(searchString)
                    || s.genre.Contains(searchString)
                    || s.genre.StartsWith(searchString)
                    || s.genre.EndsWith(searchString)
                    || s.synopsis.Contains(searchString)
                    || s.synopsis.StartsWith(searchString)
                    || s.synopsis.EndsWith(searchString)
            }
      

Open in new window

0
ow to merge multiple list values in one list values.

For example,

List<string> List1 = new List<string> {"A","B","C"}; // Some times null value also

List <string> List2 = new List<string> {"D","E","F"}; // Some times null value also

List <string> List3=  null;  // Some times null value also

My Query is below :

 List<string> ArrAllValue = List1.Concat(List2.Concat(List3))
                                                               .Where(x => !string.IsNullOrEmpty(x)) //probably
                                                               .ToList();

Error : Value Cannot be null
0
I want to find the columns from my table based on my input string.

for example,

my table as below.



So, First i want to find the columns of "Lesson x SUB A" and the get the values of that..

My Result is = 400..

How to write LINQ Query or C# code..?

DataTable table = new DataTable();
table.Columns.Add("Lesson1 x SUB A");
table.Columns.Add("Lesson1 x SUB B");
table.Columns.Add("Lesson1 x SUB C");
table.Rows.Add(400,500,600);
table.Rows.Add(300, 400, 500);
table.Rows.Add(500, 600, 700);
string Findcolumns = "Lesson1 x SUB A";

Open in new window


Below is the simple Query.

string result=table.Rows[0][Findcolumns].ToString();

Open in new window


But, how to give where condition in the query.

because, i have "n" number of rows and i want to filter based on the conditions..

for example,

DataTable table = new DataTable();
table.Columns.Add("Lesson1 x SUB A");
table.Columns.Add("Lesson1 x SUB B");
table.Columns.Add("Lesson1 x SUB C");

table.Columns.Add("UNIT");

table.Rows.Add(400,500,600,205);
table.Rows.Add(300, 400, 500,300);
table.Rows.Add(500, 600, 700,400);

Open in new window


Where unit = 400.
0
How to find the exact particulate word from a string using LINQ.

MyString = "10"-550-HO-004-01-12XVRU-XA";

MyPositionNo(Input)  : 4

Result : 004

MyPositionNo(Input)  : 1

Result : 10"

Also,

this is not matching word. This needs to be find the position (Index) of the string to get.

Example.

InputParam = 4 (it means 4th position of my string)

So, 4th position is : 004 (MyString = "10"-550-HO-004-01-12XVRU-XA")

004 ==> is my 4th position want to fetch.

1st position is : 10" (MyString = "10"-550-HO-004-01-12XVRU-XA")

10" ==> is my 1st position want to fetch.
0
Below codes is to return .net datatable, and I use asp.net repeater to bind it. everything is working except the list does not sort by date and time. The data source starts from query3.

Not sure why. and hope some experts can help out.

Thanks

var query3 = query1.Concat(query2).OrderBy(z => z.DateTimeSent);

           


             
public static DataTable GetConversation(string sid, string token,string accountPhoneNo, string twilioPhoneNo)
        {  
            string clientPhoneNo = string.Empty;
            string inputFilePath = filePathUserMessagesAll;
            DataTable dt = new DataTable();
            dt.Clear();
            dt.Columns.AddRange(new DataColumn[]
           {
                new DataColumn("Body",typeof(string)),
                new DataColumn("DateCreated",typeof(string)),
                new DataColumn("Direction",typeof(string)),
                new DataColumn("SelectedPhoneNo",typeof(string))
           });
            XDocument xdoc = null;
            using (XmlReader xr = XmlReader.Create(inputFilePath))
            {
                xdoc = XDocument.Load(xr);
                var query1 = from t in xdoc.Descendants("User")
                             where 
                             (
                             t.Element("From").Value.ToLower() == "+1" + accountPhoneNo.ToLower()
                             ) //client phone
                             select new
                             {
                   

Open in new window

0
Hello Experts,
I need help converting a SQL query to LINQ, to use in my C#.Net application.
Please provide a query that returns a sql value, and one that returns a list (please see code below).

SELECT OutPutPath FROM  [dbo].[ProcCon] PC
INNER JOIN ProcType PT ON
PT.TypeID = PC.TypeID
WHERE PT.Name = 'TimeInterval'

Open in new window


Thank you,
mrotor
0
Hi,

I done some sample code which should search matching record and display in specified format.

i am unable to get exact format.

my output is : 100,300 (because only matching ENGLISH H and MATHS L)

see my sample code's
0
Important Lessons on Recovering from Petya
LVL 10
Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Hi Experts!

Need your help updating LINQ query.

The LINQ query should return a distinct record of locationId and phonenumber.
Then which need to extract locationId and phonenumber and store it in local variables.

SQL Query:

SELECT DISTINCT  
       personlocation.LocationID,
       phone.PhoneNumber
FROM dbo.personProducts pp
     INNER JOIN dbo.personPhonesLocations phoneLocation ON pp.personLocationRecID = phoneLocation.personLocationRecID
     INNER JOIN dbo.personLocations personlocation ON pp.personLocationRecID = personlocation.personLocationRecID
     INNER JOIN dbo.Phones phone ON phoneLocation.PhoneID = phone.PhoneID
     INNER JOIN dbo.PhoneTypes PhoneTypes ON pl.PhoneTypeID = PhoneTypes.PhoneTypeID
WHERE pp.PersonNumber = 'ABC123'
      AND PhoneTypes.PhoneTypeName = 'Contact Number'

Open in new window


C# method:
var personPhone = (from pp in dataContext.personProducts
from phoneLocation in dataContext.personPhonesLocations
from personLocation in dataContext.personLocations
from phone in dataContext.Phones
from phoneType in dataContext.PhoneTypes
where pp.PersonNumber == "ABC123" && phoneType.PhoneTypeName == "Contact Number"
select new
{
LocationId = personLocation.LocationID,
phonenumber = phone.PhoneNumber
}).Distinct();


if (personPhone != null)
{
    string locationId = ???; <-- need help
    string phonenumber = ??  <-- need help

}

Open in new window


TIA!
0
How to return row based on finding columns and its value

List<string> Str = [0] Sub A=100

                              [1] Sub B=80

now i want to find the column of Sub A and Sub B in my datatable.

If column found then find the row of the above column values for condition basis.

for example (as per example data table).

   Sub A value is 80 ==> this should check in between Sub A(MN) and Sub A(MX) &&
   Sub B value is 100 ==> this should check in between Sub B(MN) and Sub B(MX)

5. Final result would be return true/false (sample example returns true)

Tried below Query

                          string[] str = { "Sub A=80, Sub B=100"}; // Range should check between range of minimum and maximum of both subjects

  DataTable dt = new DataTable();
        dt.Columns.AddRange(new[] { new DataColumn("TYPE"),new DataColumn("Sub A(MN)"), new DataColumn("Sub A(MX)"), new DataColumn("Sub A(MN)"),
new DataColumn("Sub B(MX)") ,new DataColumn("Sub A") ,new DataColumn("Sub A1"),new DataColumn("FROM"),new DataColumn("TO"),new DataColumn("DEPT") });
        dt.Rows.Add(null, "100", "1000", "100", "100", null, null, 20, "100", "S6");
        dt.Rows.Add(null, "200", "2000", "200", "200", "200", "200", "35", "100", "S7");
        dt.Rows.Add(null, "100", "1000", "100", "100", "100", "100", "35", "100", "S7");
        dt.Rows.Add(null, "100", null, null, "100", "100", "100", "35", "100", "S7");
        dt.Rows.Add(null, "100", "1000", "100", null, null, "100",…
0
Hi,

How to find and search list values which is available or not from multiple another lists.

For example,

 List<string> FromList = new List<string>() { "Sub A", "Sub B" };
        List<string> List1 = new List<string>() { "Sub A=80", "Sub D=70" };
        List<string> List2 = new List<string>() { "Sub B=100", "Sub C=90" };

I want to take Fromlist and check this will be available or not in List1 and List2.

if it is available then it returns result as Sub A=80 and Sub B=100.

if it is not available in both list (List1 and List2) then it returns false.

How to form in LINQ Query..?
0
How to I add "or" to the following:

 var recordCount = db.tblWHQReports.Count(a => a.Mgr == employeeid);

??
0
Hi ,

I am passing list value into the datatable.

I want to find the column first and then check whether the value exist or not for that columns.

I want to write in LINQ Query as bool true/false

for example,

string str ABSCHECK = ABS A#ABS B // input value

string[] words1 = str.Split('#'); //Splitting the values

words1[0] ABS A //list

           [1] ABS B

The above two value is a column name and i want to check in the below table.

 DTTABLE :

A      ABS A(MN)      ABS A(MX)      ABS B(MN)      ABS B(MX)      ABS C(MN)      ABS C(MX)
100      100      100      100      100      100      100
For ABS A ==> Matching two columns and values present(like ABS A(MN) and ABS A(MX))

For ABS B ==> Matching two columns and values exists (like ABS B(MN) and ABS B(MX))

So i want to return result is true.

if nothing is matching, it means (column not identified and value not present) returns false.

How to write LINQ..?

below is my query

string str ABSCHECK = ABS A#ABS B // input value

string[] words1 = str.Split('#'); //Splitting the values

bool results = (from r in DTTABLE.AsEnumerable()
                           select r.Field<string>(words1.ToList())); // to find out columns and value

but not working..?
0
I have a record in sql server 2016 that has two time(0) columns.  I need to do a query with linq that returns the id when the current time is between the 2 stored times (starttime and endtime).

any help appreciated.

string now = DateTime.Now.ToString("HH:mm:ss");

            var result = (from s in db.Shifts
                          where s.StartTime >= DateTime.Parse(now) &&
                          s.EndTime <= DateTime.Parse(now)
                          select s.ShiftId);

Open in new window

0

LINQ Query

526

Solutions

388

Contributors

Language Integrated Query (LINQ) is a Microsoft .NET Framework component that adds native data querying capabilities to .NET languages, although ports exist for Java, PHP, JavaScript and ActionScript. LINQ extends the language by the addition of query expressions, which are akin to SQL statements, and can be used to conveniently extract and process data from arrays, enumerable classes, XML documents, relational databases, and third-party data sources.

Top Experts In
LINQ Query
<
Monthly
>