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

I am needing to compare values in two lists which are different types. What I need to do is find out if the AttendeeID is in both lists. If it is in both lists then do nothing, however, if the AttendeeID is not in both lists then we need to add that information to another list. I was trying to use LINQ to do this, however, I'm not doing something correctly and I'm not sure as to where I'm wrong. Below is the code that I currently have.

If TypeOf e.Item Is GridDataInsertItem Then
        
            'Remove individuals from list if they exist already in the outcome memos table before binding the list.
            Dim newClients As RadDropDownList = CType(e.Item.FindControl("rdlClientNames"), RadDropDownList)
            Dim getAllClients As New IndividualsBase
            Dim indList As List(Of IndividualsBase) = getAllClients.SelectIndividuals(0,True,Nothing,0)

            Dim getIndividuals As New OutcomesMemos
            Dim indMemo As List(Of OutcomesMemos) = getIndividuals.SelectOutcomeMemos("Active")
            Dim totalInds As List(Of IndividualsBase)

            indMemo = indMemo.Where(Function(xMemos) Not indList.Contains(xMemos.AttendeeID)).ToList()

            If totalInds.Count = 0 Then
                Dim list As New RadDropDownList
                list.Items.Item(0).Text = "All Individuals Have Been Added"
            Else
                newClients.DataSource = totalInds
                newClients.DataTextField = "FullNameID"
                

Open in new window

0
[Webinar On Demand] Database Backup and Recovery
LVL 11
[Webinar On Demand] Database Backup and Recovery

Does your company store data on premises, off site, in the cloud, or a combination of these? If you answered “yes”, you need a data backup recovery plan that fits each and every platform. Watch now as as Percona teaches us how to build agile data backup recovery plan.

We have a huge list (say 100,000) which needs to be converted to DataTable for SqlBulkcopy.

Can you guide what could be the fastest way to do this without using for loop? For now we are doing it like - in below code listDos is object list

using (var dataTable = new DataTable(dataTableName))
{
    dataTable.Locale = CultureInfo.CurrentCulture;
    var columns = new[]
        {
             new DataColumn("Id", typeof(int)),
             new DataColumn("FkId", typeof(int)),
             new DataColumn("Status", typeof(string)),
             new DataColumn("RecordFrom", typeof(DateTime))
        };

    dataTable.Columns.AddRange(columns);


    foreach (ObjectDo listDo in listDos)
    {
        var row = dataTable.NewRow();

        if (rebuildDo.Id != null) row["Id"] = rebuildDo.Id;

        if (rebuildDo.FkId!= null) row["FkId"] = rebuildDo.FkId;

        row["Status"] = rebuildDo.Status;

        row["RecordFrom"] = rebuildDo.RecordFrom;

        dataTable.Rows.Add(row);
    }

    return dataTable;
}

Open in new window

0
I am trying to create a select list ...that basically just creates a user entry for my user to select options to be inserted into the database.

I have this in my controller...which Is not complete  Here roles is a list of value and label.....What am I missing here..and how would you then use this to display on view....to I need something in my view model as well?

       private IEnumerable<SelectListItem> GetRoles()
        {
            IContactEntityEditService contactEntityEditService = DependencyResolver.Current.GetService<IContactEntityEditService>();
            List<string> roles = contactEntityEditService.GetContactLinkedEntitiesRoles();
           
            roles.Select(x => new SelectListItem
                                {
                                    Value = x.value,
                                    Text = x.label
                                });

            return new SelectList(roles, "Value", "Text");
        }

Open in new window

0
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
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
The codes below is working ok. I just need to make VAR response to be sorted.
How can I do that?

   public static List<Make> GetVehicleMakeList()
        {
            List<Make> lstMake = new List<Make>();
            HttpClient objClient = new HttpClient();
            try
            {
                var response = objClient.GetStringAsync(Utility.Enumeration.vehicleMakeAPICall).Result;
                if (!string.IsNullOrEmpty(response))
                {
                    VehicleMakeAPIResponse objMakeResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<VehicleMakeAPIResponse>(response);
                    return objMakeResponse.Results;
                }

            }
            catch (Exception ex)
            {

                //log error message here
            }
            return lstMake;
        }

Open in new window

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
Get your problem seen by more experts
LVL 11
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

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
This is fragment of my .cs code

        public arAbonamenty_page()
        {
            InitializeComponent();
 

            Nexo_ARWALEntities myNexo_ARWALEntities = new Nexo_ARWALEntities();

            Nullable<Int32> grupa_tw = new Nullable<Int32>();
            grupa_tw = null;
            short? kiedy_fakturować_combo = new Nullable<Int16>();
            bool? bool_okres_płatności = new Nullable<bool>();
            if (okres_płatności.SelectedIndex == 2)
            {
                bool_okres_płatności = null;
            }
            else
                bool_okres_płatności = Convert.ToBoolean(okres_płatności.SelectedIndex);

            Nullable<bool> kiedy_fakturować = new Nullable<bool>();
            kiedy_fakturować = Convert.ToBoolean(kiedy_fakturować_combo);

            var query = (from myabonamenty in myNexo_ARWALEntities.ArAbonamenty
                         join nexotowary in myNexo_ARWALEntities.Asortymenty
                         on myabonamenty.nexo_towar equals nexotowary.Id
                         join myklienci in myNexo_ARWALEntities.ArKlienci
                         on myabonamenty.id_klient equals myklienci.id_klient
                         where (grupa_tw == null || (grupa_tw != null && nexotowary.Grupa_Id == grupa_tw))
                         where (myabonamenty.czy_fa_auto_na_początku_okresu == null || (kiedy_fakturować != null && myabonamenty.czy_fa_auto_na_początku_okresu == kiedy_fakturować))

                         

Open in new window

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
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
Receive 1:1 tech help
LVL 11
Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

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

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!