We help IT Professionals succeed at work.

LINQ Query

633

Solutions

456

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.

I have this Grid in my c# application

The Display Value in column 1  has an ID and Description  ( see  screen below)

Selected Record From Combo Box withing Grid

When i change values in column1 I want the description written into column2

I am trying to use LINQ  and a LAMDA Expression  . My script is as shown below

[private void dgvDetailsTable_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 1)
            {

                switch (this.dgvDetailsTable.Columns[e.ColumnIndex].Name)
                {
                    case "dgvcmbarsaleditemid":
                        var result = ((List<InventoryItemModel>)dgvcmbarsaleditemid.DataSource).Find(x => x.INVITEMId.Equals(dgvcmbarsaleditemid.Selected));
                        this.dgvDetailsTable.CurrentRow.Cells[2].Value = result.INVITEMDescription;
                       

                        break;


                }
            }
        }[/code]

My database  field name is INVITEMId   and my   DataGrid  column 1 name is   dgvcmbarsaleditemid.


In the debugger  I can see that the 1188 records  were selected  and in the debugger i can see the loop search going on

See  Debugger  Screen below

Debugger Screen showing that I have ALL the 1188 records in my List

At the end of the looping it can not find the selected record and put it in the result variable even though the selected record
is on screen and coming from the database.  See  Error screen below

Error Screen with result  variable having null
0
// returns back an ienumerable of string containing each user
 var users = list.Where(x => x.Field.Equals("assigned_to")).GroupBy(y => y.Value).Select(z => z.Key);

// returns back an ienumerable of result for this hard coded user
var testUser = statList.Result.Where(x => x.GroupByFields.Any(y => y.Value.Equals("Test User")));

Instead of hardcoding "Test User" I need to look up all of the values returned in users from above.
0
I have a Linq query that looks like:
int[] state = ...;

                var rowsIndices = state
                    .Select((value, index) => new
                    {
                        Discriminator = index / 9,
                        Description = $"row #{index / 9 + 1}",
                        Index = index,
                        Row = index / 9,
                        Column = index % 9
                    })
                    .GroupBy(tuple => tuple.Discriminator);

Open in new window

And I would like to put this in a method which returns rowsIndices:
public ??? GetRowIndicies(int[] state)
{
            return state
                .Select((value, index) => new
                {
                    Discriminator = index / 9,
                    Description = $"row #{index / 9 + 1}",
                    Index = index,
                    Row = index / 9,
                    Column = index % 9
                })
                .GroupBy(tuple => tuple.Discriminator);
}

Open in new window

Except I don't know what to put for ???
Is it possible to return this Linq query as a method result?

Visual Studio gives the following:
Visual Studio rowsindicies
0
Hi Experts!

Need your help with the following query.

In jobHistories, for each City, for each Perid, how would you filter the linq query to return the following condition: if Hired = "Y" then select one of the record with Hired = "Y" and ignore the rest of the records for PerId. If there are no Hired= "Y" then just select one record for the PerId
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject2
{

    [TestClass]
    public class UnitTest3
    {
        internal class JobHistory
        {
            public int PerId;
            public string JobTitle;
            public string Address;
            public string Hired;
            public string City;
            public Nullable<System.DateTime> CreatedOn;
        }

        [TestMethod]
        public void Extract_HiredThenEverythingElse_CorrectPicks2()

        {
            // Arrange
            List<JobHistory> jobHistories = new List<JobHistory>()
            {
                new JobHistory() {PerId = 1, JobTitle = "Knight", Address = "123 Street", Hired = "Y", City = "Yokohama", CreatedOn = new DateTime(2011, 6, 1)},
                new JobHistory() {PerId = 1, JobTitle = "Cook", Address = "234 Street", Hired = "Y", City = "Yokohama", CreatedOn = new DateTime(2012, 6, 1)},
                new JobHistory() {PerId = 1, JobTitle = "Mechanic", Address = "345 Street", Hired = "N", City = "Yokohama", CreatedOn = 

Open in new window

0
Hi Experts!

Need help with the following linq query:

            //For each City, For each person, if the JobTitle is EITHER Knight, Cook, Mechanic we want to take all the records for the Person for that City,

            //For each City, For each person, if there's a duplicate JobTitle with the same address then just take one

Below is a mock up unit test with test data.


using Microsoft.VisualStudio.TestTools.UnitTesting;

using System;

using System.Collections.Generic;

using System.Linq;

 

namespace UnitTestProject2

{

 

    internal class JobHistory

    {

        public int PerId;

        public string JobTitle;

        public string Address;

        public string City;

        public Nullable<System.DateTime> CreatedOn;

    }

 

    [TestClass]

    public class UnitTest2

    {

        [TestMethod]

        public void Extract_PersonByJobTitleByCriterias_Success()

        {

            // Arrange

            List<JobHistory> jobHistories = new List<JobHistory>()

            {

                new JobHistory() {PerId = 1, JobTitle = "Knight", Address = "123 Street", City = "Sapporo", CreatedOn = new DateTime(2011, 6, 1)},

                new JobHistory() {PerId = 1, JobTitle = "Cook", Address = "234 Street", City = "Sapporo", CreatedOn = new DateTime(2012, 6, 1)},

                new JobHistory() {PerId = 1, JobTitle = "Mechanic", Address = "234 Street", City = "Sapporo", CreatedOn = new DateTime(2012, 12, 1)},

 

              

Open in new window

0
Hi,

My between date is not working

I'm only getting one record instead of three

I don't know what I'm doing wrong.

I tried without parsing it and that didn't work.

        public DateTime FromCreatedDate { get; set; }
        public DateTime ToCreatedDate { get; set; }

list = list.Where(x => x.CreatedDate >= DateTime.Parse(model.FromCreatedDate.ToString()) && x.CreatedDate <= DateTime.Parse(model.ToCreatedDate.ToString()));

Open in new window

0
Hi,

I need your help please!!!

 I want to say if the user enter in GroupTxt a range from 10 -30 the linq query will return the result within that range.


HTML Code
<select name="GroupListID" class="btn btn-default dropdown-toggle" id="GroupListID">
                            <option value="">Select an Option</option>
                                    <option value="3">Dx</option>
                                    <option value="5">Group ID</option>
                                    <option value="4">NPI</option>
                                    <option value="6">Plan Code</option>
                                    <option value="1">Px</option>
                        </select>


                         @Html.TextBoxFor(x => x.GroupTxt, new { @class = "form-control", @style = "width:100%" })

Open in new window



Database
Table: RuleDetail
if (model.SelectedGroupID != null && model.GroupTxt != null)
                     list = list.Where(x => model.GroupTxt.Any(m => Equals(x.ConditionAttributesAndValues, m)));
              
                      // here I want to say 
                      //  and 
                      // and if the user enter a range in the textbox then filter all that are within the range.

Open in new window



ConditionAttributesAndValues is varchar(1000)

the data inside the ConditionAttributesAndValue looks like this:

<br> IF Dx = aa (299.00,<br>299.01,<br>299.80,<br>299.81,<br>299.90,<br>299.91,<br>99999)  <br> AND Dx Between Range (10 - 30) <br>(aa22)<br>"aa55"<br>

Open in new window


so is there a way to search for Dx range and see if what the user enter in the textbox is within the range in the database field called ConditionAttributesAndValue?
0
Hi,

I'm working with linq and need your help please.

I have a string[] SelectedVersion that I pass from my view to the controller.

I want the linq to return query that contain the string SelectedVersion[]

list = _unitOfWorkCABusinessRules.RuleDetailRepo.GetAll().ToList();

list = list.Where(x => x.Version.Contains(model.SelectedVersion));

model.SelectedVersion is a string array 
x.Version is a string 

Open in new window



the error says: " I cannot convert string [] to string "

how can I solve this syntax?
0
Hi Experts!

Need your help.
In C# LINQ how do you get the latest enrollment and return a List that's ordered by PerId?

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

namespace UnitTestProject2
{

    internal class Enrollment
    {   public int  PerId;
        public string Class;
        public Nullable<System.DateTime> DateFrom;
    }

    [TestClass]
    public class UnitTest2
    {
        [TestMethod]
        public void LinqQuery()
        {
            //Arrange
            List<Enrollment> latestEnrolled = new List<Enrollment>()
            {
                new Enrollment() {PerId = 1, Class = "Chemistry", DateFrom = new DateTime(2018, 1, 1)},
                new Enrollment() {PerId = 1, Class = "Modern Drama", DateFrom = new DateTime(2017, 1, 1)},
                new Enrollment() {PerId = 1, Class = "Math 302", DateFrom = null},
                new Enrollment() {PerId = 3, Class = "Physics", DateFrom = new DateTime(2016, 1, 1)},
                new Enrollment() {PerId = 3, Class = "Comp 101", DateFrom = new DateTime(2017, 1, 1)},
                new Enrollment() {PerId = 3, Class = "Music", DateFrom = new DateTime(2017, 6, 1)},
                new Enrollment() {PerId = 2, Class = "Leadership", DateFrom = null},
                new Enrollment() {PerId = 2, Class = "Film Study", DateFrom = new DateTime(2017, 1, 1)},
                new Enrollment() {PerId = 2, Class = "Microbiology",

Open in new window

0
Hi,

I have some procedural .NET core code I would like to convert to Linq - or at least get as close as I can.

From the code below have "group_list" generated via linq.

Thanks,

Ward.

using System;
using System.Collections.Generic;
using System.Linq;

namespace Linq_Test1
{
    class Email_Message
    {
        public string From;
        public string From_Address;
        public string Subject;
        public DateTime TimeRecieved;
        public string Body;
        public string Message_ID;
    }

    class Email_Group
    {
        public string From;
        public string From_Address;
        public List<String> Message_ID_List = new List<string>();
        public String Combined_Body;
    }
    class Program
    {
        static void Main(string[] args)
        {
            List<Email_Message> message_list = new List<Email_Message>();
            List<Email_Group> group_list = new List<Email_Group>();

            Email_Message message;

            message = new Email_Message();
            message.From = "A"; message.From_Address = "a@test.com"; message.Subject = "Subject 1";
            message.TimeRecieved = DateTime.Now; message.Body = "Body A-1"; message.Message_ID = Guid.NewGuid().ToString();
            message_list.Add(message);

            message = new Email_Message();
            message.From = "A"; message.From_Address = "a@test.com"; message.Subject = "Subject 2";
            message.TimeRecieved = DateTime.Now; message.Body = 

Open in new window

0
Hi,

This is my first linq and I'm not sure what I'm doing.

I need your help please.

I have to tables:

Table:
CABR_RuleIdentifier
RuleIdentifierId
RuleSetId
RuleIdentifier
IsActive


Table:
CABR_RuleDetail
RuleDetailId
isActive
RuleSetId
RuleIdentifierId
Version
Environment


I need to do this in linq:

SELECT RuleDetailId, isActive, RuleSetId, RuleIdentifierId, Version, Environment
FROM CABR_RuleDetail
LEFT JOIN CABR_RuleIdentifier
ON CABR_RuleDetail.RuleSetId = CABR_RuleIdentifier.RuleSetId; 


           CABR_RuleDetail RuleDetailResult = new CABR_RuleDetail();
            var result = from CABR_RuleDetail in RD
                         join CABR_RuleIdentifier in RI
                         on RD.RuleSetId equals RI.RuleSetId into ResultData
                         from RuleDetailResult in ResultData.DefaultIfEmpty()
                         select new
                         {
                             CABR_RuleDetail.RuleDescription,
                             CABR_RuleDetail.RuleDetailId,
                             CABR_RuleDetail.isActive,
                             CABR_RuleDetail.RuleSetId,
                             CABR_RuleDetail.RuleIdentifierId,
                             CABR_RuleDetail.Version,
                             CABR_RuleDetail.Environment,
                             CABR_RuleIdentifier.RuleIdentifier
                         };

Open in new window

0
Hi Experts,
I want to convert this simple query to a LINQ query in C#.
select distinct c.MemberID,max(c.approved)  from Claims c
join member m on c.MemberID = m.MemberId
where m.Id = 910318 and  c.PointsEarned > 0 group by c.MemberID

Open in new window

Any help is appriciated!
Thanks in advance.
0
Hi,

I have two linq query's and i'd like to combine them and want to create a single linq query.

I searched o net and found some examples but i didn't succeeded.

Any help would be grateful for me.



 
           var objects = Pre.ModelBase.GetExpressList((simpackcomslvLib.IScrModelBase)Pre.Spck.CurrentModel, true);

            var filteredObjects = from e in objects
                                  group e by Pre.NamedObject.GetNamedObjectModelType((simpackcomslvLib.IScrNamedObject)e);

            var filteredObjectsII = from e in objects
                                    where Pre.Expressions.ChannelType(e) == "REAL"
                                    group e by Pre.Expressions.GetChannelBaseName(e.fullName);

Open in new window


First i would like to group like below;

group e by Pre.NamedObject.GetNamedObjectModelType((simpackcomslvLib.IScrNamedObject)e);

Open in new window

and then

group element where it matchs with my statement

                            where Pre.Expressions.ChannelType(e) == "CUTF"
                                    group e by Pre.Expressions.GetCutForceChannelBaseName(e.fullName);

Open in new window

0
Hi,

Please advise what is wrong in my linq query. Also, please advise if there is any better way of doing below.
I need contact where preferredContactIndicator is true.
if preferredContactIndicator":true is not available then first array of contact needs to be available.

My C# code below
var querycontacts = 
                        from cont in profile.contact
                        where cont.preferredContactIndicator == true
                        select cont;

                    if (querycontacts != null)
                    {
                        member.ContactType = cont.contactNumberType;
                        member.CountryCode = cont.isdCode;
                        member.ContactNumber = cont.contactNumber;
                    }else if (profile.contact != null && profile.contact.Count > 0)
                    {
                        member.ContactType = profile.contact[0].contactNumberType;
                        member.CountryCode = profile.contact[0].isdCode;
                        member.ContactNumber = profile.contact[0].contactNumber;
                    }

Open in new window


JSON snippet below, removed unnecessary JSON to simplify:
{
   "contact":[
      {
         "contactNumberType":"HOME",
         "isdCode":"+86",
         "areaCode":"10",
         "contactNumber":"6755555",
         "preferredContactIndicator":true
      },
      {
         "contactNumberType":"MOBIL",
         "isdCode":"+86",
         "areaCode":"10",
         "contactNumber":"67029354"
      }
   ]
}

Open in new window


Error says
cont.contactNumberType;
 const does not exists.
Please correct my query.
Also, please advise if c# code can be written in better way

Thanks
0
I'm looking for a C# LINQ statement that will return all pairs from a list.

I've seen solution of the form:
var combinations = from item1 in list
                   from item2 in list
                   where item1 < item2
                   select Tuple.Create(item1, item2);

Open in new window

My problem is the (item1 < item2). What if these are objects that can't be compared?

The non-Linq solution would be something like:
for (int I=0; I < list.Count; ++I)
    for (int j = I+1; j < list.Count; ++j)
        pairs.Add(new Pair(list[I], list[j]);

Open in new window


So if list = {a,b,c,d,e}
the pairs would be:
{a,b}
{a,c}
{a,d}
{a,e}
{b,c}
{b,d}
{b,e}
{c,d}
{c,e}
{d,e}

(An item is not paired with itself)
And we don't want both {a,e} and {e,a}. Just the first one.
0
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
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

LINQ Query

633

Solutions

456

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!