LINQ Query

612

Solutions

446

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

Need help in converting the usage of the foreach to using a lamda expression to get the list of pets.

 //Looking for something like this acutalPets = people............ToList();

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.Linq;

namespace SampleTest
{
    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public List<Location> Locations { get; set; }
    }

    public class Location
    {
        public string PetType { get; set; }
        public bool HasPets { get; set; }
    }

    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            //Arrange
            List<Person> people = new List<Person>() {
                new Person() {FirstName = "FirstName01", LastName = "LastName01",
                              Locations = new List<Location>() {
                                  new Location() { HasPets = false}
                              }
                },
                new Person() {FirstName = "FirstName02", LastName = "LastName02",
                              Locations = new List<Location>() {
                                  new Location() { PetType = "Dog", HasPets = true }
                              }
                },
                new Person() {FirstName = "FirstName03", LastName = "LastName03",
                              

Open in new window

0
OWASP: Threats Fundamentals
LVL 13
OWASP: Threats Fundamentals

Learn the top ten threats that are present in modern web-application development and how to protect your business from them.

Hi
I'm trying to add items to a flowlayoutpanel  something like the picture

kate.JPG
I've managed a picture but the hover is failing because BigPicturePath is being overwritten
so
1. How do I use the picture.tag to pass the url into ThumbPictureBox_MouseHover method
2. How Do I adjust the linq query to order on movies.movielinkpersons.role

3. In order to create the picture example I'm guessing I'd need to create a 2 X 2 TableLayoutPanel with Col1 rowspan of 2 adding a Picture box to col1 a label to col2 row1 (with a click function) and a button to Col2 Row2

What concerns me is my form has a 3 column TableLayoutPanel with a second TableLayoutPanel  in the center column with the flowlayoutpanel   in 1 cell show here

FilmForm.JPG
In the code bellow GetCast is triggered on clicking a title  in a listview

        private void GetCast(int id)
        {
            using (var context = new MoviesEntities())
            {
                var Movies =  context.movielinkpersons.Where(p => p.movieId == id).ToList();
                int i = 1;
                foreach(var person in Movies)
                {
                    string Thumb = "";
                    if (person.person.profile_path == "/JohnWayneBig.png")
                    {
                        Thumb = ImgPath + "JohnWayneSml.png";
                        BigPicturePath = ImgPath + "JohnWayneBig.png";

                    }
                    else
                 

Open in new window

0
Hi Experts!

Have a User class that implements IComparable<User>. What this gives us is the ability to sort on the list w/o having to create another list by FirstName.

    internal class User : IComparable<User>
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }

        public int CompareTo(User other)
        {
            return this.FirstName.CompareTo(other.FirstName);
        }
    }

Open in new window


It looks users.Sort() works, but users.Reverse() doesn't work. Any ideas how to fix this?

Here's the entire code.
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject1
{
    internal class User : IComparable<User>
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }

        public int CompareTo(User other)
        {
            return this.FirstName.CompareTo(other.FirstName);
        }
    }
    
    [TestClass]
    public class UnitTest1
    {
        List<User> users;

        [TestInitialize]
        public void StartUp()
        {
            users = new List<User>()
            {
                new User() {FirstName = "Sally", LastName = "Jones", Age = 30},
                new User() {FirstName = "Yu", LastName = "Lan", Age = 40},
                new User() {FirstName = "Sook", LastName = "Kim", Age = 20},
            

Open in new window

0
I have the below c# code where I am trying to get a list of Message but I am getting the error below on the last line of the code
System.FormatException: 'Index (zero based) must be greater than or equal to zero and less than the size of the argument list.'

I am new to linq so I am sure I am missing something.  Any help would be appreciated .  thanks!

var query = from message in _messageRepository.GetMessage()
                    select new Message()
                    {
                        MessageCode = message.MessageCode,                        
                        Description = String.Format(message.FriendlyMessageText, value)
                    };
            return query.ToList();

Open in new window

0
How to sort order by descending using Linq query in the DataTable?

DataTable Dt2 populates data .. and has the data.. I am trying to resort the data in the Dt2.

DataTable Dt2 = new DataTable();
            Dt2 = dt.AsEnumerable()
                .GroupBy(r => r.Field<string>("City"))
                .Select(g =>
                {
                    var row = dt.NewRow();
                    row["City"] = g.Key;
                    row["rating"] = g.Average(r => ParseInt32(r.Field<string>("rating")));
                    return row;
                }).CopyToDataTable();


            var results = from r in Dt2.AsEnumerable()                           
                            select new
                            {   
                                City = r.Field<string>("City"),
                                rating = r.Field<int>("rating")
                            };

Open in new window

0
Hi Experts,

I have this LINQ query.
var LockCounterQuery = (from s in _MemberFailedSignInRepository.Table where s.UserName == UserName select s.LockCounter); 

Open in new window


How do I get the value of lock counter? Tried to use something like this -
LockCounterQuery.FirstOrDefault().ToString()

But didn't work.
Thanks in advance!
0
How can I use LINQ to go through a list of Points using this formula?

I'm confident I know how to build a function for it but I really like LINQ and I believe it's a prime candidate for this calculation. I'm currently reading about it.

        List<Point> PolyPoints = new List<Point>();
        PolyPoints.Add(new Point(3, 4));
        PolyPoints.Add(new Point(5, 11));
        PolyPoints.Add(new Point(12, 8));
        PolyPoints.Add(new Point(9, 5));
        PolyPoints.Add(new Point(5, 6));

Open in new window


Shoelace algorithm
0
Hi,

I have the following code. How can I avoid foreach using linq?

foreach(var number in phoneNumbers)
{
	foreach(var i in number.key)
	{
		if(students[i].phone == null)
		{
			students[i] = new People { phone = number.Value };
		}
		else
		{
			students[i].phone = number.Value;
		}
	}
}

Open in new window


please note
Dictionary<string[], string> phoneNumbers
List<People> students
0
Hello,
This bt of code is in LINQ for :
If we have to pass message int by int as query params
eg ?message=1&message=2&message=4&message=0&message=0&message=7

 sy.Code.Length == code.Length && sy.Code.Select((c, i) => new { c, i }).All(v => v.c != code[v.i]);

Open in new window


Any suggestions on how to write it if we can pass all the param in a single string

Thanks
0
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
Amazon Web Services
LVL 13
Amazon Web Services

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

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
Angular Fundamentals
LVL 13
Angular Fundamentals

Learn the fundamentals of Angular 2, a JavaScript framework for developing dynamic single page applications.

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,

Anyone please can suggest if in Linq I can select records .I am trying  to get  some data as list.
So for example in the attached worksheet if i can get list of data before NULL value yellow cell  of ColumnA.  Please assume this as a DataTable with columns.

Just need an idea of a linq query and c sharp.

Thanks.
abhilash
Book1.xlsx
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

LINQ Query

612

Solutions

446

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
>