LINQ Query

617

Solutions

451

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!

Have the following pretend mock up complex model; need help in getting the list of cities from the complex model with Linq (do not want Lamda answer).

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

namespace UnitTestProject2
{

    internal class Example01
    {   public string Country;
        public List<Example02> States; //Location
    }
    internal class Example02
    {
        public string State;
        public List<Example03> Cities; //Plan
    }
    internal class Example03
    { public string city; }


    [TestClass]
    public class UnitTest2
    {
        [TestMethod]
        public void ComplexModel_GetvaluesInsideComplexModel_3Records()
        {
            //Arrange
            Example01 usa = new Example01()
            {
                Country = "usa",
                States = new List<Example02>()
                {
                    new Example02()
                    {
                        State = "Texas",
                        Cities = new List<Example03>()
                        {
                            new Example03() { city = "Austin"},
                            new Example03() { city = "Odessa"},
                            new Example03() { city = "Lubbock"}
                        }
                    },
                    new Example02()
                    {
                        State = "Georgia",
                        Cities = new 

Open in new window

0
Fundamentals of JavaScript
LVL 19
Fundamentals of JavaScript

Learn the fundamentals of the popular programming language JavaScript so that you can explore the realm of web development.

Hi,

How can I use LINQ to remove entries from one list of items matching values from another list.

Please the code below for more details.

Thanks,

Ward

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Xml.Serialization;
// using ClosedXML.Excel;

using ClosedXML.Excel;
using DocumentFormat.OpenXml;
using ExcelHelper;

namespace Linq_Test_1
{

    public class Person
    {
        public int Index { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }

}
    class Program
    {
        static void Main(string[] args)
        {
            var rand = new Random();
            var people = Enumerable.Range(0, 100).Select((x, i) => new Person { Age = rand.Next(1, 101), Name = $"Name{x}", Index = i }).ToList();
            var results = people.OrderByDescending(x => x.Age).ToList();

            List<int> remove_list = new List<int>();

            for (int i=1;i<=20;i++)
            {
                int random_key = rand.Next(1, 101);
                remove_list.Add(random_key);
            }

            // <-- How to do the code below via Linq -- RemoveAll?

            List<Person> new_list = new List<Person>();

            foreach (Person p in people)
            {
                bool matched_flag = false;

                foreach (int key in remove_list)
                {
                    if 

Open in new window

0
Hi,

How can I take the results of a Linq Query and convert to XML and save to file.

I have provided some same code below.

Thanks,
Ward

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

namespace Linq_Test_1
{

    class Person
    {
        public string Name;
        public int Age;
    }
    class Program
    {
        static void Main(string[] args)
        {
            List<Person> People = new List<Person>();

            Random rnd = new Random();

            for (int i=1;i<=100;i++)
            {
                Person person = new Person();

                person.Name = "Name" + i.ToString();                
                person.Age = rnd.Next(1, 101);
                People.Add(person);
            }

            int counter = 1;
            var results = from Person in People orderby Person.Age descending
                         select new
                         {
                             Name = Person.Name,
                             Age = Person.Age,
                             Index = counter++ 
                         };


        }
    }
}

Open in new window

0
I have two lists:
List<A> listA of objects A
List<B> listB of objects B

I also have a method which can take any pair of A and B and return a Boolean True or False:
bool TestAB(A a, B b)

Open in new window


Now I want to process all possible combinations of elements from listA and ListB,
for each pair {a, b} if TestAB(a, b) returns True then add element a to List<A> listApass, and add element b to List<B> listBpass. No duplicates in listApass or listBpass.


The other variation on this idea is if I have one listA of A elements and I want to process all possible pairs of elements from the same list (n things taken 2 at a time). This time I have a method TestAA(A a1, A a2) which returns a Boolean true or false, and I want to make a list of all pairs of elements for which the test is true (so I'd need a class which holds a pair of AA, we'll just call that class AA, it holds a pair of {a1, a2}, and we'll have a List<AA> listAA which is a list of all the pairs.)


(If that doesn't make enough sense, then here's how it would be done in CE# without Linq:
List<A> listA = new List<A>{ a1, a2, a3 }
List<B> listB = new List<B>{ b1, b2, b3 }

List<A> listApass = new List<A>();
List<B> listBpass = new List<B>();

foreach(A a in listA)
{
    foreach(B b in listB)
    {
        if (TestAB(a, b))
        {
            listApass.Add(a);  // but only if listApass does not already contain a
            listBpass.Add(b);  // but only if listBpass does not already contain b
        }
    }
}

Open in new window


I suspect there's a nice Linq way of doing this.

And for the second related question, the old C# code would be something like:
var listA = new List<A>{ a1, a2, a3 }
var listAA = new List<AA>();

for (int i=0; i < listA.Count; ++i)
{
    for (int j = i+1; j < listA.count; ++j)
    {
        if (TestAA(listA[i], listA[j]))
        {
            listAA.Add( new AA(listA[i], listA[j]) );
        }
    }
}

Open in new window

Again I assume this is something Linq would be well suited for. (I'm just not familiar with Linq yet.)
Thank you!
0
How could this be done with Linq?
The code loops through all a.b[i].c with index i.

Can i say: Give me a collection of all a.b[i].c for all i (index)?
0
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
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
Rowby Goren Makes an Impact on Screen and Online
LVL 19
Rowby Goren Makes an Impact on Screen and Online

Learn about longtime user Rowby Goren and his great contributions to the site. We explore his method for posing questions that are likely to yield a solution, and take a look at how his career transformed from a Hollywood writer to a website entrepreneur.

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
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
Amazon Web Services
LVL 19
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.

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

LINQ Query

617

Solutions

451

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
>