how to fetch the data from list where id =4,7 in c# [Resolved]

Posted by Kasani007 under C# on 6/1/2016 | Points: 10 | Views : 535 | Status : [Member] | Replies : 3
how to fetch the data from list where id =4,7 in c# (Lambda Expression)




Responses

Posted by: A2H on: 6/2/2016 [Member] [MVP] Silver | Points: 50

Up
0
Down

Resolved
You can ofcourse use where as well. FindAll() is a function on the List type , but where is a linq extension method.

Regarding the performance wise where will perform slightly faster when the list having larger number of records as where will return lazily evaluated results, by lasily means if you are looking for id where will look for the first match and discard other and return results

You can check this thread for more details
http://stackoverflow.com/questions/1531702/findall-vs-where-extension-method

Thanks,
A2H
My Blog

Kasani007, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: A2H on: 6/1/2016 [Member] [MVP] Silver | Points: 25

Up
0
Down
You can use the below code
var result = addr1.FindAll(j => ((j.Id == 4) || (j.Id == 7)));


Complete Sample Code
List<Addresses> addr1 = new List<Addresses>();
//Loading dummy values
Addresses objAddress = new Addresses();
objAddress.Id = 1;
objAddress.Address = "Test Address1";
addr1.Add(objAddress);

Addresses objAddress2 = new Addresses();
objAddress2.Id = 2;
objAddress2.Address = "Test Address2";
addr1.Add(objAddress2);

Addresses objAddress3 = new Addresses();
objAddress3.Id = 3;
objAddress3.Address = "Test Address3";
addr1.Add(objAddress3);

Addresses objAddress4 = new Addresses();
objAddress4.Id = 4;
objAddress4.Address = "Test Address4";
addr1.Add(objAddress4);

Addresses objAddress7 = new Addresses();
objAddress7.Id = 7;
objAddress7.Address = "Test Address7";
addr1.Add(objAddress7);

var result = addr1.FindAll(j => ((j.Id == 4) || (j.Id == 7)));

foreach (Addresses obj in result)
{
//Loop through results and use the values

}


Class
public class Addresses
{
public long? Id { get; set; }
public string Address { get; set; }
}


Sample Working Demo : https://dotnetfiddle.net/0LMsYV

Thanks,
A2H
My Blog

Kasani007, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Kasani007 on: 6/2/2016 [Member] Starter | Points: 25

Up
0
Down
hi A2H,

shall i use var result = addr1.Where(j => ((j.Id == 4) || (j.Id == 7)));

then what is the difference ?

Kasani007, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response