Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x

LINQ Query

541

Solutions

395

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

Hi,

I want to merge two data sheets with different columns in c#..

For example,

Based on my sheets and column mention, it should merge the data and display in final output as datatable.

Sheet1 ==> columnA data and columnC data

sheet3 ==> columnD data and Column F data

datatable result ==> merge of ColumnA & ColumnC as one column

                               merge of ColumnD & ColumnF as another column

my input string is sheet and column.

for example,

inPut string Sheets ==> "Sheet1" and "Sheet3"

Input string Columns ==> ColumnA & ColumnC(Sheet1)

                                       ColumnD & ColumnF(Sheet3)...

How to form code in either LINQ or C#..?
0
Keep up with what's happening at Experts Exchange!
LVL 11
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 split and get value based on my count.

For example,

I have inputcount = 2
MyString = "ABC_21-NIM-3547-789_23-278";

i want to get the final string is "ABC_21-NIM". because my input is "2". so i want to split("-") and get the values.

so final output after   splitting
 ABC_21-NIM ( here ABC_21 is first string and NIM is second string)

how to form the values using LINQ C#.?
0
It really is a simple question yet finding so much trouble with Google finding how to do it. After the where clause I want to return the results from my strongly typed dataset table with a parameter passed from a parameter with vb.net and how to call it. If you can assist I would appreciate it.

Bolded is where I think it should go. But I clearly don't know how to say it. "test" would be something like
"row.Item(columnname) IsNot DBNull.Value AndAlso row.Item(columnname) = filter AndAlso row.TT_Rec_ID = Template_ID" just for example. But the way I see it we should be able to pass anything through that is LINQ compatible.

Function Global_Table_Query([b]ByVal test As Predicate(Of ds2.JOINEDDATADataTable[/b])) As DataTable
        ErrorMessage = ""

        Dim dt As New DataTable
        Dim Is_Good As Byte = 1
               Dim thread As New Task(
  Function()
      Try

          Dim lowNums = From row In Global_Table
                        [b]Where test
[/b]                        Select row


          dt = lowNums.CopyToDataTable
                    Return dt
      Catch ex As Exception
          ErrorMessage = ex.Message
          Return Nothing
      Finally

      End Try
  End Function
            )

        Dim tasks() = {thread}
        Array.ForEach(tasks, Sub(tx) tx.Start())
        Task.WaitAll(tasks)

        For Each tsk In tasks

            Select Case True

                Case tsk.IsCanceled
                    Is_Good = 1

                

Open in new window

0
Hi,

I have two data table and i want to return duplicate rows in second table if any duplicate found for same combination.

if does not match rows then it should return as below

dttable.png
the above example empno and sub1 from TAB1 should check in TAB2.

if both match then no need to worry.

if doesn't match the particular row (101 and A) then we should return rows from TAB2

below is my sample code.

but, it shows some error..

where is problem in my code...?

 foreach (DataRow row in dt1.Rows)
         {
            EmpNo = row["EmpNo"].ToString();
            Sub1 = row["Sub1"].ToString();

            var duplicates = dt2.AsEnumerable()
            .GroupBy(dr => row["EmpNo"].ToString() && row["Sub1"].ToString())
            .Where(g => g.Count() > 1)
            .Select(g => g.First())
            .ToList();

            
         }

Open in new window


pls. check my code...?
0
Hi,

currently i am using SQL Server table in one of my application.

But, my client asking me to change the table to excel file or ini file which is located in server path.

the reason is to change to excel or ini file is, my client doesn't have access to change the name of the value in table.

For example,

Table structure is below.

EmpNo      Sub1      Sub2      Sub3      Sub4
1      100      200      400      500
2      200      300      400      500
3      400      500      300      400
instead of the above table client's want to maintain in excel which need to be read from the folder.

see my sql code.

SqlCommand cmd = new SqlCommand(@"select Sub1,Sub2,Sub3 where Empno=@EmpNo", sqlcon);
                    cmd.Parameters.Add("@EmpNo", SqlDbType.NVarChar).Value = cmbEmp.SelectedItem.ToString();

 the same i want to convert and read from excel or ini.

How to change..?
0
Hi Experts,
I am getting an error in LINQ expression that I use in MVC.net with C#.net code behind application.
It's complaining about how I am handling a null date value.
I need help resolving this error

Here is the error:

An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code

Additional information: LINQ to Entities does not recognize the method 'System.DateTime Parse(System.String)' method, and this method cannot be translated into a store expression.


Here is my code:
            List<DataObject.HS> _lstTasks = new List<DataObject.HS>();
            using (CDO.CAEntities db = new CDO.CAEntities(new Security().getConnectionString(1), UserID, ID))
            {
                _lstTasks = (from m in db.HS
                             select new DataObject.HS
                             {
                                 ID = (int)m.ID,
                                 IssueDescription = m.IssueDescription,
                                 ResolvedDate = m.ResolveDate == null ? DateTime.Parse("1/1/1900") : (DateTime)m.ResolveDate,
                             }).ToList();
            }
            return _lstTasks;

Open in new window

0
Even if no recipients are checked and this clears all of the recipients in the grid, this is as expected.
Please find the code file in text file.
cody12345.txt

Image
0
How to add a new plan if state name = 'NJ' and type name = 'Term Life'? and carrier name = 'Mutual of Omaha' using c#?


plan name="test"
plan id = "123"
plan healthtier="test"

<Products>
	<State Name="NJ">
		<Type Name="Subsidized">
			<Carrier Name="Chip" ID="100000008">
				<Plan Name="Chip" ID="100000322" HealthTier="" />
			</Carrier>
		</Type>
		<Type Name="Term Life">
			<Carrier Name="Mutual of Omaha" ID="100000017">
				<Plan Name="Term Life Express" ID="100000259" HealthTier="" />
		 	</Carrier>
		</Type>
		
	</State>
<State Name="PA"> 
		<Type Name="In Market">
			<Carrier Name="2017 Capital Blue Cross" ID="100000134">
				<Plan Name="Silver PPO 4500/0/10" ID="100002633" HealthTier="Silver" />
		 	</Carrier>
			<Carrier Name="2017 Geisinger Health Plan" ID="100000135">
		 	</Carrier>
		 			
		</Type>
		<Type Name="Out Market">
			<Carrier Name="2017 Capital Blue Cross" ID="100000134">
				<Plan Name="Gold PPO 1000/0/20" ID="100002634" HealthTier="Gold" />
			</Carrier>
			<Carrier Name="2018 Capital Blue Cross" ID="948120063">
				<Plan Name="Gold PPO 1000/0/20" ID="100002634" HealthTier="Gold" />
			</Carrier>  
		</Type> 
		<Type Name="Term Life">
			<Carrier Name="Assurity" ID="100000005">
				<Plan Name="Non-Med Term 350" ID="100000230" HealthTier="" />
			</Carrier> 
		</Type> 
	</State>
</Products>

Open in new window

0
var query =
     (from c in [b]db.productInfo[/b]
     where [b]c.flavor[/b] == "Classic Coke" && [b]c.container[/b] == "Can"
     select new { c.co2Target }).Single();

Open in new window


Can the parts in bold be decided at runtime?

In other words, I want to use a context.<Table> and use LINQ lambda expression to do a select on the table, but I don't know which table until runtime.

Can I pass in the name of the table as a string into a method, and then inside the method use a lambda expression to do a select on <table name passed in> ?  Build the lambda expression dynamically?
0
I want to do the same thing as the code below -- but using LINQ in C# ( LINQ to SQL ) to do the iterating and inserting.  Please provide exact C# code.  The broader question is how to do basic CRUD operations in LINQ.  I do have a context called "Model1":

I want just very simple statements ... nothing complex.  Just basic CRUD operations.

I managed to get a SELECT working .. but I am not sure how to do an INSERT or UPDATE.


 using (var db = new Model1())
 {
//do a select
var query = from b in db.Customers
                            orderby b.CustID
                            select b;

                //    //Console.WriteLine("All blogs in the database:");
                foreach (var item in query)
                {
                    Console.WriteLine(item.CustID);
                }
}

 using (var db = new Model1())
 {
// do the insert 
}

 using (var db = new Model1())
 {
// do the update
}

 using (var db = new Model1())
 {
// do the delete 
}

Open in new window


private void btnInsert_Click(object sender, EventArgs e)
{
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        string constring = @"Data Source=.\SQL2008R2;Initial Catalog=AjaxSamples;Integrated Security=true";
        using (SqlConnection con = new SqlConnection(constring))
        {
            using (SqlCommand cmd = new SqlCommand("INSERT INTO Customers VALUES(@CustomerId, @Name, @Country)", con))
            {
                cmd.Parameters.AddWithValue("@CustomerId", row.Cells["Id"].Value);
                cmd.Parameters.AddWithValue("@Name", row.Cells["Name"].Value);
                cmd.Parameters.AddWithValue("@Country", row.Cells["Country"].Value);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }
    }
    MessageBox.Show("Records inserted.");
}

Open in new window

0
Free Tool: SSL Checker
LVL 11
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Hi

I use VB.net to connect to a SQL database.

I have a order table, and a orderline table.

Dim recOrderHeaders As IList(Of ShopifyData.OrderHeader)

            recOrderHeaders = (From item In dbContext.OrderHeaders
                               Where (item.CustID = MyCustomer.CustID)
                               Order By item.OrderNo Descending
                               Select item).ToList

' Then I iterate through all the orders and find the order lines
for each item in recOrderHeaders
   for each oLine in recOrderheaders.Orderlines
   next
next

Open in new window


Iteration through order headers go quickly, but iteration through order lines takes a long time (on my case 60ms per line).

I thought all data was collected in the OrderHeader object from memory when using the ToList.

Typically each order has 1-5 lines.

How can I speed this up ? For example one customer has 90 orders and it takes 5 seconds to get all orders/orderlines.
0
Hi experts
I'd some research on comparing two lists of integers but can't find the things I need.

I have two lists of integers. User will only have the old list.
I would like to determine a course of actions that instructs a user how to produce the new list from the old list.

eg.
old list:  1 2 3 4
new list:5 7 2 3 4

What I need are actions such as:
1) Remove item "1" from index 0
2) Add item "5" to index 0
3) Add item "7" to index 1

Thanks in advance

PS. I am using .NET 4.0
0
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
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
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
Become an Android App Developer
LVL 11
Become an Android App Developer

Ready to kick start your career in 2018? Learn how to build an Android app in January’s Course of the Month and open the door to new opportunities.

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,

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
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

LINQ Query

541

Solutions

395

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
>

No Top Experts for this time period. Answer questions to earn the title!