LINQ Query

602

Solutions

438

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 have following codes.
I have myCollection variable that contains all the Web elements.  I am using two paths using XPath and or('|') operator because I need different things from the objects that these two different paths gives.
From the elements from the first path(//div[@role='region' and //@my-label] ), I want to get Text properties.
From the elements from the second path(//button[@role='button' and //@my-label]), I want to get the values of 'my-label' attributes. (the Text properties for this elements are "")
After that, I want to put all these too myList<string>.
Obviously I am getting errors on my Linq query(at Select statement).
What's should I do to accomplish this?


public IReadOnlyCollection<IWebElement> myCollection => _driver.FindElements(By.XPath("//div[@role='region' and //@my-label]  | //button[@role='button' and //@my-label]"));

var myList = new List<string>();
myList = myCollection
                    .Select(a => a.Text or a => a.GetAttribute("my-label").ToString()) 
                    .Reverse() // Newest item first
                    .Where(a=>!String.IsNullOrEmpty(a))
                    .Where(b=>!String.IsNullOrEmpty(b))                              
                    .ToList();

Open in new window

0
Introduction to Web Design
LVL 13
Introduction to Web Design

Develop a strong foundation and understanding of web design by learning HTML, CSS, and additional tools to help you develop your own website.

Hello EE,

Im trying to do this linq query :


            Dim qx = (From m In MyItems
                         Where arrString.All(Function(v) m.Value.Contains(v))
                         Let row = rowID
                         Let myKey = m.Key
                         Let myValue = m.Value
                     ).OrderBy(Function(n) n.myKey) _
                      .Select(Function(t) New With {t.row, t.myKey, t.myValue})

Open in new window



it does not stops while running my software, but if I place a breakpoint, and I try to see whats inside "qx", it says : Error Type expected"

the goal is to return 3 variables, (Row, myKey, myValue),  thats why I cannot do  .ToDictionnary() or .ToList()  I thought I needed to do Select New With since I have more than 2 varaibles

also I wanted to OrderBy in my LINQ
do you see any problem looking at it ?
0
Hi,

I am working on C# and used Linq.

How can I factor my below code? It has too many foreach


        foreach (var category in Model.ArrivalBooking.AvailableProducts.Where(t => t.Products.Any(x => ((x.IsVisible == true) && (x.ProductType == "C")))).OrderBy(b => b.SortOrder))
                {
                    if (category.CategoryCode == "MNG" || category.CategoryCode == "TRN")
                    {
                        foreach (var product in category.Products.Where(t => t.ProductType == "C" && t.IsVisible == true).OrderBy(x => x.Rate))
                        {
                            if (coreServicesRules.ProductCodeList.Contains(product.ProductCode))
                            {
                                productDetailsInGrid = productDetailsInGrid.Replace("@@PRODUCTCODE@@", product.ProductCode);
                                productDetailsInGrid = productDetailsInGrid.Replace("@@PRODUCTCODEAEDRATE@@", product.Rate.ToString());
                            }
                        }
                    }
                }

Open in new window


Please advise.
0
Hi,

I am working on C# .Net project.

How I will make Linq query if I need to find the data from List object which is inside List?

public class CoreServicesRules
    {
        public List<CoreServicesProductDetails> CoreServicesProductList { get; set; }
    }


    public class CoreServicesProductDetails
    {   
        public List<string> ProductCodeList { get; set; }
        public string ReplaceProductCodeFromString { get; set; }
        public string ReplaceProductRateWithString { get; set; }
    }

Open in new window

     
      Now I wanted to check data from
      
	public List<string> ProductCodeList { get; set; }

Open in new window

     

      and I have object for CoreServicesRules
      
      
      I wanted to see if ProductCodeList contains "My product Code".
      
      Please help me with the query.
0
I have a list defined from the script below


List<MonthlyVariationsModel>  variationsList = GlobalConfig.Connection.GetAllVariationsThisperiod();
variationsList =  variationsList.Where(x => x.Staff_no == StaffNoParameter.Text).ToList();

Open in new window


The list is generated and the LINQ  where  clause selects  the required  record

I now need to put selected records  into my List

The List name is   StaffVariationList.

The List Definition is as below

 public string StaffVariationList
        {
            get
            {
                return $" {Staff_no} {Ent_type}  { Ent_code } {Mnthyear} {Subrunno} {Grade_amt } {Companycode}";
            }
        }

Open in new window


My problem is how to  convert/read  the variationlist  generated from the LINQ  query into the StaffVariationList above

i think i may need  foreach clause   but do not know the correct syntax

My  previous post on generating the list may be useful

Any help will be appreciated

Olukay
0
I have 2 Lists
1 Staff  List
2 Staff Variations List

I want be able to select a staff  and limit the entries in the variations List
to records for this staff  only. (see atached screen for the 2 Lists)

I have been able to select the staff and have shown the selected staff no N003  in the debugger

In trying to pass the value N003  to the LINQ  Query   I am having a syntax error

I have tried  to use Intellisense as far as possible but  somehow I have this syntax error
highlighted

Please  see  attached word file that gives a step by step activity  and all debugger values
including the syntax error  in the LINQ Query

I will appreciate any  input into how to get the LINQ Query  syntax right

Thanks

Oluwole
VariationsScreen08022019.PNG
SCRIPT-SELECT-STAFF-AND-LIMIT-STAFF.docx
0
I want to find matches and deltas between 3 lists combined
List<string> a = {1, 2, 3, 4, 5}
List<string> b = {2, 5, 6, 7}
List<string> c = {3, 7, 8, 9}

Open in new window

0
I need to use LINQ  in my application (See code  Below)

            FormNameLabel.Text = this.Name;
            Companylabel.Text = LoginDetails.staticcompany;
            RoleLabel.Text = LoginDetails.staticrole;

The 3 items above are just parameters which are all correct though I only need 1 of them for my LINQ  query  
All the variables are  strings          


            // Do a list for this company only
            List<AbseCodeModel> results = new List<AbseCodeModel>();
            results = results.ToList();
            results = results.Where(x => x.Companycode = Convert.ToString(Companylabel.Text)).ToList;

Please note that LoginDetails is a static class  but it returns the correct value for  LoginDetails.staticcompany

The results = results.ToList();  executes  correctly  BUT  whenever i substitute the line with the where clause
i run into syntax issues

Whether I  pass  Companylabel.Text  or  LoginDetails.staticcompany into the where clause  it gives an error

I think  its my syntax for the Where Clause that has a problem

Attached is the word showing the error list

How can I resolve this

Thanks


Olukay
LINQQuerySyntax28-12-2018.PNG
0
I am trying to maintain a sequence counter in a table per another column, i will call [AssetId]

I need to LINQ to Entities in C#

Trying something like this
int? iAssetId=1

var nextSequence = db.Failures.Where(w=> w.AssetId== iAssetId).Max(x => (int?)x.NextSequence ?? 0) + 1;

Open in new window


SQL table looks like this
CREATE TABLE [dbo].[Failures] (
      [Id] [int] IDENTITY(1,1) NOT NULL,
      [AssetId] [int] NULL,
      [NextSequence] [int] NULL
)

this must work if there is no current AssetId and it  is null
0
Hi This is following on from here

As a learning exercise I'm retrieving and updating an XML file of TV show  information  

It occurred to me that it's possible to have multiple seasons to the same TV show so I adjusted the XML accordingly
TV.XML
<?xml version="1.0"?>
<TV>
  <Show>
      <Name>MacGyver 2016</Name>
      <FolderName>MacGyver 2016</FolderName>
      <TMDBid>67133</TMDBid>
      <Season>
        <SeasonNumber>3</SeasonNumber>
        <Episode>
          <EpisodeNumber>1</EpisodeNumber>
          <EpisodeName>Improvise</EpisodeName>
          <BackDrop>https://image.tmdb.org/t/p/w350_and_h196_bestv2/eQMVJkBltvID73sh9vvTistssS6.jpg</BackDrop>
          <FullPath>J:\Media\TV\MacGyver (2016)\S03\Macgyver.2016.S03E01.Improvise.mp4</FullPath>
        </Episode>
      </Season>
      
  </Show>
</TV>

Open in new window


Of course this broke the LINQ query from the previous so answer

How do adjust the select query bellow to retrieve Episode data which is now nested in Season?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace XmlReader
{
    class Program
    {
        static void Main(string[] args)
        {
            // Load the XML Document using Linq to XML
            var xdoc = 

Open in new window

0
C++ 11 Fundamentals
LVL 13
C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

Hello!

I have a simple SQL query in a c# project that I have to convert to LINQ but am struggling with it due to my very limited experience and understanding of LINQ queries.  What's stumping me is how to handle the summing and grouping.  This is a pretty time sensitive project for me and once I see how it's done I'll be able to understand and build on it.
Here is the query:
SELECT Dept, Shift, ShiftDate, FLOOR(SUM(RunningGoal)) AS Target, SUM(UnitsProd) AS Produced 
FROM Vw_PRODCOUNTER_HourlyProduction 
WHERE Dept = '3500A' AND Shift = '1' AND ShiftDate = '12/13/2018' GROUP BY Dept, Shift, ShiftDate

Open in new window

Thanks for your time and help in advance.  Have a good day!
JeffH
0
I have this SQL Code and converted to the below LINQ to Entities.  I generated the LINQ code but think there must be a better way.  I am trying to implement a Sequence column value.   The table already has an identity column and  a sequence for each item

SELECT MAX(COALESCE(FailureSequence, 0)) + 1 AS NextSequence
FROM FunctionalFailures
WHERE(FunctionalAnalysisId = 2);

Open in new window


and this LINQ

from FunctionalFailures in
(from FunctionalFailures in db.FunctionalFailures
where
  FunctionalFailures.FunctionalAnalysisId == 2
select new {
  Column1 = ((Int32?)FunctionalFailures.FailureSequence ?? (Int32?)0),
  Dummy = "x"
})
group FunctionalFailures by new { FunctionalFailures.Dummy } into g
select new {
  NextSequence = (g.Max(p => p.Column1) + 1)
}

Open in new window

0
Hello Experts.

I'm afraid this question might be a little vague, but I'm almost certain that it is possible to do.

Basically, I want to build a LINQ query in my vb.net project that compares two object's key fields and reports back which ones in Object A are NOT in Object B, and vice versa.

More specifically, I have a non-databound DataGridView which contains a current list of member ID's (Object A). I also have a bound DataGridView that contains an older dataset (say for example last week's member ID's).

To be perfectly honest, every time I read about SQL joins, my mind turns into a pretzel, but I feel that it's time I overcome this mental block and try to get a handle on the difference between and inner-join and an outer-join.

So, if anyone has a good example of a LINQ query that might be close to what I've described above, I would be interested in seeing what that looks like.

Always Learning,
Tony G.
0
Hello Experts.

I'm hoping to find a better method for defining a LINQ query that can programatically determine which column/field to return.

I was actually able to do this fairly easily using SQL:
cmd.CommandText = "SELECT DISTINCT ? FROM Scoring WHERE LS = ?"
cmd.Parameters.Add(New OleDbParameter("@Param1", SL_Clmn))
cmd.Parameters.Add(New OleDbParameter("@Param2", LoserTP))

Open in new window

As you can see in the above SQL command, I want to retrieve the value of a specific column which needs to be initially defined as a string (in this case, the SL_Clmn variable).

Since LINQ only allows variables to be used in the WHERE clause and not the SELECT clause, I'm not able to specify which column I want from the selected row.

So right now, my code looks like this:
' LsrMP: Loser Match Points, LsrNo: Player 1 or 2
Dim LsrMP As Int32 = 0, LsrNo As Int32 = IIf(TN = 1, 2, 1)
' WnrMP: Winner Match Points, WnrNo: Player 1 or 2
Dim WnrMP As Int32 = 0, WnrNo As Int32 = IIf(TN = 1, 1, 2)
' LoserSL: Loser's Skill Level
Dim LoserSL As Int32 = CInt(PT(SK, LsrNo).Text)
' SL_Clmn: Skill Level Column (L1 through L9)
Dim SL_Clmn As String = "SL" & CStr(LoserSL)
' LoserTP: Loser's Total Points (out of 20)
Dim LoserTP As Int32 = CInt(PT(MP, LsrNo).Text)
'
Dim ScoreData =
(
   From getPoints In Me.sData.Scoring
   Where getPoints.LS = LoserTP
   Select getPoints
).ToList
'
For Each row In ScoreData
   Select Case SL_Clmn
      Case 1 : LsrMP = row.SL1
      Case 2 : LsrMP = row.SL2

Open in new window

0
Dear Experts,

I have a data table in a dataset in vb.net code. the data table has four columns customerid, month,  ActiveDays, Purchase_Amt

I want to sum  ActiveDays and  Purchase_Amt by customer (total  ActiveDays and Purchase_Amt by customer)

I am thinking of using LINQ, but i have not yet gotten how to go about it.

Help

Anthony
0
What is the syntax for a LINQ query that would get the first value from a JSON child node. I'm trying to get the first value in the "aenHistory" element in the attached JSON sample.

Here is the query that works fine so far apart from the "FormerAEN" element:

                                    studentDataBatch =
                                                  (from people in students.Children().Children()                                                    
                                                   select new studentSIM
                                                   {
                                                       PersonID = (people.SelectToken("StudentBasic.studentId") == null ? String.Empty : people.SelectToken("StudentBasic.studentId").Value<string>()),
                                                       Surname = people.SelectToken("StudentBasic.surname").Value<string>(),
                                                       Forename = people.SelectToken("StudentBasic.firstName").Value<string>(),
                                                       AEN = (people.SelectToken("StudentBasic.aen") == null ? String.Empty : people.SelectToken("StudentBasic.aen").Value<string>()),                                                      
                                                      Sex = (people.SelectToken("StudentBasic.gender").Value<string>()).Substring(0,1),
                                                     …
0
Hi,

   The SQL query below is a sample to show how to do SQL Pagination Without using OFFSET.

            SELECT foo, bar, baz, quux FROM table
            WHERE oid NOT IN(SELECT oid FROM table
                                ORDER BY title ASC LIMIT 50 )
            ORDER BY title ASC LIMIT 10

How would I translate such query into Linq, if we consider we would have a class named "TableClass" binded to that table "Table"?

Linq
EFCore
SQLite

Thanks,
Claude
0
Actually in the case of web application, there will be 2 dropdownlists will be avaliable. Example: Country,City. Based on the selection of country the cities drop down list need to be populate. But actually the data from the dropdownlist are avaliable at xml file.And here populating the values from xml file need to write in LINQ Queries.

 protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            var cities = (from x in xDocument.Descendants("countries").Descendants("country")
                        where x.Value==DropDownList1.SelectedValue
                        select new { x=x.Elements("city") }).ToList();
            DropDownList2.DataSource = cities;
            DropDownList2.DataTextField = "x";
            DropDownList2.DataValueField = "x";
            DropDownList2.DataBind();
         
        }
i had written another way as well but here also iam getting count as 0
(from x in xDocument.Descendants("countries").Descendants("country").Elements("city")                          
where x.Parent.Value.ToString()==DropDownList1.SelectedValue                          select new { x=x.Value }).ToList();
i had written code as seen above. but iam getting count as 0.as the data in xml file was present. please suggest
0
I have a dataset that has parents and children that I am calling branches.  Sample dataset:

Branch   TreeId    Name      ParentId
Root        1            GRP A       NULL
Root        2            SET A1      1
Child       6            SET A1B    2
Child       7            SET A1C    2

I then have a TreeId parameter that I need to pull from that level down to the children.  This set will not go higher than a Root record where ParentId IS NULL.  So what I am trying to do is let's say I pass in TreeId 1 in this case I would want the whole set back.   Essentially any ParentId = Null can have additional roots under it.   If I pass treeid = 2 I would want records 2,6 and 7.   If I pass treeid 6 or 7 I would just want that record.

Thanks for any help with the linq to achieve this if I have this all in one dataset coming in and the param treeid.
0
OWASP: Avoiding Hacker Tricks
LVL 13
OWASP: Avoiding Hacker Tricks

Learn to build secure applications from the mindset of the hacker and avoid being exploited.

I need to convert a list to Float[,] array

I have the following classes and data

 public class ThermalData
    {
        public int X { get; set; } //image pixel position x (X-Coordinate)
        public int Y { get; set; } //image pixel position y (Y-Coordinate)
        public double T { get; set; }  //pixel data (Temperature reading)
}


public class FlirImage
{
  public int Width { get; set; }
  public int Height { get; set; }
  public IList<ThermalData> ThermalData{ get; set; }
}

Open in new window


I currently have a list of each pixel in a 320x240 image that contains an instance of TemperatureData class, which contains the x,y coordinates on image, and the pixels heat reading.

I now need to convert this data a float array without looping through each pixel, is there a very fast efficient linq way of doing this?

This is what i have
thermal
And I need something like this
thermal2
based on the last image, it would be:

 [X-Coordinate, Y-Coordinate] | Temperature reading


Any ideas how i do this?
0
I have the below Linq query to retrieve a provider record with the related primary specialty.

I need to modify this to also include a secondary specialty which is coming out of the same DB table, but with a flag isSecondary set and assign the values to two new properties on the ProviderDetail object.

I'm thinking this is another .SelectMany but having trouble making it work.


DBContext.Provider
			.GroupJoin(DBContext.ProviderSpecialties, p => p.providerId, ps => ps.providerId, (x, y) => new { Provider = x, ProviderSpecialties = y })
			.Where(w => w.Provider.providerId == providerId)
			.SelectMany(x => x.ProviderSpecialties.Where(w => w.isPrimary == true)
			.DefaultIfEmpty(), (x, y) => new { Provider = x.Provider, ProviderSpecialties = y })
			.Select(m => new ProviderDetail
			{
				providerId = m.Provider.providerId,
				licenseNumber = m.Provider.licenseNumber,
				licenseExpiration = m.Provider.licenseExpiration,
				licenseStateId = m.Provider.licenseState,
				licenseStateName = m.Provider.State.abbreviation,
				firstName = m.Provider.firstName,
				lastName = m.Provider.lastName,
				title = m.Provider.Title1.name,
				primarySpecialtyName = m.ProviderSpecialties.Specialty.epicName,
				primarySpecialtyId = m.ProviderSpecialties.specialtyId == null ? 0 : m.ProviderSpecialties.specialtyId
                                //secondarySpecialtyName = ???,
                                //secondarySpecialtyId = ???
			}).FirstOrDefault();

Open in new window

0
Hi Experts,

I have a query:

var TonerTotal = (from r in _recyclingRepository.Table
                  where r.Created < date && r.Approved != null &&
                  Constants.TonerIds.Contains(r.RecyclingPackagingId)
                  select r.Quantity).Sum();

Open in new window


When the query returns null it goes to error.  How can I handle it? When the query returns null I want TonetTotal=0 otherwise TonetTotal should be the value returned.

Thanks in advance.
0
Hi All,
Advance thanks!
i am using vs2017, c#
Am using List of objects[10]. have to pick object 9 from list and insert in between 1 and 2..

List<TestClass> list = new List<TestClass>()
{
    new TestClass() { FirstColumn="1",SecondColumn = "2", ThirdColumn = "3"  },
    new TestClass() { FirstColumn="q",SecondColumn = "w", ThirdColumn = "e"  },
    new TestClass() { FirstColumn="a",SecondColumn = "s", ThirdColumn = "d"  },
    new TestClass() { FirstColumn="1",SecondColumn = "s7", ThirdColumn = "d"  },
    new TestClass() { FirstColumn="2",SecondColumn = "s6", ThirdColumn = "d"  },
    new TestClass() { FirstColumn="3",SecondColumn = "s5", ThirdColumn = "d"  },
    new TestClass() { FirstColumn="4",SecondColumn = "s4", ThirdColumn = "d"  },
    new TestClass() { FirstColumn="5",SecondColumn = "s3", ThirdColumn = "d"  },
    new TestClass() { FirstColumn="6",SecondColumn = "s2", ThirdColumn = "d"  },
    new TestClass() { FirstColumn="7",SecondColumn = "s1", ThirdColumn = "d"  },
};

Open in new window


now how to insert  FirstColumn="6" in beween 3 and 4
like this

List<TestClass> list = new List<TestClass>()
{
    new TestClass() { FirstColumn="1",SecondColumn = "2", ThirdColumn = "3"  },
    new TestClass() { FirstColumn="q",SecondColumn = "w", ThirdColumn = "e"  },
    new TestClass() { FirstColumn="a",SecondColumn = "s", ThirdColumn = "d"  },
    new TestClass() { FirstColumn="1",SecondColumn = "s7", ThirdColumn = "d"  },
    new TestClass() { FirstColumn="2",SecondColumn = "s6", ThirdColumn = "d"  },
    new TestClass() { FirstColumn="3",SecondColumn = "s5", ThirdColumn = "d"  },
    new TestClass() { FirstColumn="6",SecondColumn = "s2", ThirdColumn = "d"  },
    new TestClass() { FirstColumn="4",SecondColumn = "s4", ThirdColumn = "d"  },
    new TestClass() { FirstColumn="5",SecondColumn = "s3", ThirdColumn = "d"  },
    new TestClass() { FirstColumn="7",SecondColumn = "s1", ThirdColumn = "d"  },
};

Open in new window


Kind regards,
Pooja
0
How do I find the matches and delta's between two lists?
public class ComponentsSQLModel
{
    public string PartNoSQL { get; set; }
}

public class ComponentsExcelModel
{
    public string PartNoExcel { get; set; }
}

List<ComponentsSQLModel> sqlModel = new List<ComponentsSQLModel>();
List<ComponentsExcelModel> excelModel = new List<ComponentsExcelModel>();

Open in new window


Want to know the matches and the delta's
0
Hi,

I have a dictionary:
Dictionary<int, int> dict = new Dictionary<int, int>();

Open in new window

I want to get the key(s) that has the max value.
I used it as follow:

var max = dict.FirstOrDefault(x=>x.Value==maxValue).Key;

Open in new window


But this will return the first key only.
For example, if
maxValue=5 

Open in new window

and associated keys are 1 and 4, I want to print out both 1 and 4.

How can I accomplish this?
0

LINQ Query

602

Solutions

438

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
>