assign value using linq - c#

public class Company
{
public int id { get; set; }
public int Name { get; set; }
}
List<Company> listofCompany = new List<Company>();
this is my collection of company list I want to assign values to Name property using LINQ
listofCompany.Where(d => d.Id = 1);
(I want to assing name property of company id 1)
how do I assign it.?

using Linq would be:
listOfCompany.Where(c=> c.id == 1).FirstOrDefault().Name = "Whatever Name";
UPDATE
This can be simplified to be...
listOfCompany.FirstOrDefault(c=> c.id == 1).Name = "Whatever Name";
UPDATE
For multiple items (condition is met by multiple items):
listOfCompany.Where(c=> c.id == 1).ToList().ForEach(cc => cc.Name = "Whatever Name");

You can create a extension method:
public static IEnumerable<T> Do<T>(this IEnumerable<T> self, Action<T> action) {
foreach(var item in self) {
action(item);
yield return item;
}
}
And then use it in code:
listofCompany.Do(d=>d.Id = 1);
listofCompany.Where(d=>d.Name.Contains("Inc")).Do(d=>d.Id = 1);

It can be done this way as well
foreach (Company company in listofCompany.Where(d => d.Id = 1)).ToList())
{
//do your stuff here
company.Id= 2;
company.Name= "Sample"
}

Be aware that it only updates the first company it found with company id 1. For multiple
(from c in listOfCompany where c.id == 1 select c).First().Name = "Whatever Name";
For Multiple updates
from c in listOfCompany where c.id == 1 select c => {c.Name = "Whatever Name"; return c;}

Related

LINQ searching a List that contains a Class with objects

I'm new at C#, I know how to do a LINQ search to a List with one field/type, but not with many types of an object. I created a List
List<Reader> results = new List<Reader>();
That contain this class:
public class Reader
{
public int ID { get; set; }
public string Name { get; set; }
public string Course { get; set; }
public int Grade { get; set; }
public Reader(int id, string name, string course, int grade)
{
ID = id;
Name = name;
Course = course;
Grade = grade;
}
}
I want to search it with LINQ and match the ID and Name of a user that entered the site.
If this two fields are the same I want to take from the List the users Course and Grade.
Any suggestion how to do it ?
A simple Where for condition(s) and Select for representation should do:
List<Reader> results = ...
var data = results
.Where(item => item.ID == userID && item.Name == userName)
// .OrderBy(item => item.Course) // uncomment if you want to order by course
.Select(item => $"Course: {item.Course} Grade: {item.Grade}");
foreach (var record in data)
Console.WriteLine(record);
First, let's assume that you have two variables that hold the values introduced by the user. Those variables are userName of type string and id of type integer. If you just want a variable that holds the course and the Grade you could select a new anonymous type and do the query like this:
var values= results
.Where(item => item.ID == userID && item.Name == userName)
.Select(item => new { Course = item.Course, Grade = item.Grade });
then you could use the values like:
values.Grades
values.Course
var Selecteduser = results.Where(x => x.Name == selectedname && x.ID == ID).ToList();
if (Selecteduser.Count != 0)
{
//found match ..(Selecteduser[0])
string selectedcourse = Selecteduser[0].Course;
int selectedgrade = Selecteduser[0].Grade;
}
else
{
//coudlnt find match
}

Set the first Record Value of LINQ

I have a DBSet which is db.Company and it contains 3 records like
id name is_active
1 company1 1
2 company2 1
3 company3 1
My Created class to transfer the records:
public class CompanyFinal
{
public int id { get; set; }
public string name { get; set; }
public string selected { get; set; }
}
My LINQ looks like this:
(from h in db.Company where h.is_active == 1 select new CompanyFinal { id = h.id, name = h.name, selected = "false" }).ToList();
No doubt this LINQ is working but i need to make the first record to be selected="true" which is the company 1 while doing it in LINQ.
How could i do that? Is it possible?
Thanks in advance
Since you're making a list, I think that computational the fasted method, which is also the best maintainable (understood by others) would be to just assign the first element:
(Using method syntax, showing an alternative select)
var resultingList = db.Company
.Where(company => company.is_active == 1)
.Select(company => new CompanyFinal()
{
id = company.id,
name = company.name,
selected = "false",
})
.ToList();
if (resultingList.Any())
resultingList[0].selected = true;
If you are not sure whether you want to convert it to a list, for instance because you want to concatenate other Linq functions after it, consider using this overload of Enumerable.Select
var result = db.Company
.Where(company => company.is_active == 1)
.Select( (company, index) => new CompanyFinal()
{
id = company.id,
name = company.name,
selected = (index == 0) ? "true" : "false",
});
By the way, consider changing your CompanyFinal class such that selected is a bool instead of a string, that would make your code less error prone. For instance, after construction Selected is neither "true" nor "false". Users are able to give it a value like "TRUE" or String.Empty
If your class has users that really need a string property selected instead of a Boolean property consider keeping a get property for it:
public class CompanyFinal
{
public int id { get; set; }
public string name { get; set; }
public bool Selected {get; set;}
// for old user compatability:
public string selected
{
get { return this.Selected ? "true" : "false"; }
}
}
The following will go wrong:
if (companyFinals[0].selected == "True") ...
versus:
if (companyFinals[0].Selected)
What if we define a local variable
var counter = 1;
(from h in db.Company where h.is_active == 1 select new CompanyFinal { id = h.id, name = h.name, selected = (counter++ == 1 ? "true" :"false") }).ToList();
From your result:
var companies = (from h in db.Company
where h.is_active == 1 select h).ToList();
var companyFinals = (from h in companies
select new CompanyFinal {
id = h.id,
name = h.name,
selected = "false"
}).ToList();
var firstCompany = companies.FirstOrDefault();
if (firstCompany != null) {
firstCompany.selected = true;
}
// save result back to database
There is no way to do it in 1 operation other than writing a stored procedure.

Using Join with IQueryable LINQ

I am trying to implement Inner join query on two tables opportunityProducts and Products where I am supposed to return Iqueryable element in my MVC web API service. But from below, I am not able to get result as it throws error for conversion.
public IQueryable<OpportunityProducts> GetProductsByShipID(int id)
{
IQueryable<OpportunityProducts> oppProductss =
from c in db.OpportunityProducts
from p in db.Products
where p.ProductID == c.ProductID
select new { c.Quantity,c.ProductDesc,c.RemainingQuantity, p.QtyInHand};
return oppProductss;
}
You need to fill the Type you wish to return instead of returning an anonymous type. Here since you are querying the OpportunityProducts, I think you don't have QtyInHand property. So you can either return a new type altogether or add this property.:-
IQueryable<ResultantProducts> oppProductss =
from c in db.OpportunityProducts
from p in db.Products
where p.ProductID == c.ProductID
select new ResultantProducts
{
Quantity = c.Quantity,
ProductDesc = c.ProductDesc,
RemainingQuantity = c.RemainingQuantity,
QtyInHand = p.QtyInHand
};
I see an error in your code. You should return objects of type OpportunityProducts, I mean:
public IQueryable<OpportunityProducts> GetProductsByShipID(int id)
{
IQueryable<OpportunityProducts> oppProductss = from c in db.OpportunityProducts
from p in db.Products
where p.ProductID == c.ProductID
select new OpportunityProducts // <---- THIS!
{
Quantity = c.Quantity,
ProductDesc = c.ProductDesc,
RemainingQuantity = c.RemainingQuantity,
QtyInHand = p.QtyInHand
};
return oppProductss;
}
I hope it helps you.
Regards,
Julio
I think you can create class called ResultProducts with all properties(same data type in the original table (nullable also need to put)) what you want to get. Then you can return that object.
public class ResultProducts
{
public int Quantity { get; set; }
public string ProductDesc { get; set; }
public int RemainingQuantity { get; set; }
public int QtyInHand { get; set; }
}
public IQueryable<ResultProducts> GetProductsByShipID(int id)
{
var oppProductss =from c in db.OpportunityProducts
from p in db.Products
where p.ProductID == c.ProductID
select new ResultProducts()
{
Quantity =c.Quantity,
ProductDesc= c.ProductDesc,
RemainingQuantity=c.RemainingQuantity,
QtyInHand=p.QtyInHand
};
return oppProductss ;
}
I hope this will work.

How to get filtered list based on common items in two lists in c#

I am trying to get a list filtered based on the matches of one of the properties with a property of another list.
In below example, only the items which have common 'name' between both lists should be filtered in 1st list. Can some one tell me the most concise way of doing it?
class TCapability
{
public string Name { get; set; }
public int Id { get; set; }
}
class PCapability
{
public string Name { get; set; }
public int Code { get; set; }
}
Input:
var capability = new List<TCapability>()
{
new TCapability() {Name="a", Id=1},
new TCapability() {Name="b", Id=2},
new TCapability() {Name="c", Id=3}
};
var type2Capability = new List<PCapability>()
{
new PCapability() {Name="a", Code=100},
new PCapability() {Name="b", Code=200},
new PCapability() {Name="d", Code=300}
};
Expected Output:
capability =
{
{ Name="a", Id=1 },
{ Name="b", Id=2 }
}
var result = capability.Where(c => type2Capability.Any(c2 => c.Name == c2.Name));
you can try use join clause like this
capability = (from a in capability
join b in type2Capability on a.Name equals b.Name
select a).ToList();
UPDATE on comment if type2Capability can have duplicate names
capability = (from a in capability
join b in type2Capability on a.Name equals b.Name into f
where f.Any()
select a).ToList();
If the lists can get long then a HashSet can speed things up.
var set = new HashSet<string>(type2Capability.Select(t => t.Name));
var res = capability.Where(c => set.Contains(c.Name));

How to extract results from a Linq query?

class Program
{
static void Main(string[] args)
{
MyDatabaseEntities entities = new MyDatabaseEntities();
var result = from c in entities.Categories
join p in entities.Products on c.ID equals p.IDCategory
group p by c.Name into g
select new
{
Name = g.Key,
Count = g.Count()
};
Console.WriteLine(result.ToString());
Console.ReadLine();
}
}
How can I extract the values from ths result set so I can work with them?
foreach (var item in result)
{
var name = item.Name;
var count = item.Count;
...
}
This will only work inside the same method where the LINQ query is located, since the compiler will only then know which properties are available in the anonymous object type (new { }) used in your LINQ select.
If you return a LINQ query to a calling method, and you want to access it in the way shown above, you'd have to define an explicit type and use it in your LINQ query:
class NameCountType
{
public string Name { get; set; }
public int Count { get; set; }
}
...
return from ... in ...
...
select new NameCountType
{
Name = ...,
Count = ...,
};
For example:
foreach (var x in result)
{
Console.WriteLine(x.c.Name);
}
var results = (from myRow in ds.Tables[0].AsEnumerable()
where myRow.Field<String>("UserName") == "XXX"
select myRow).Distinct();
foreach (DataRow dr in results)
UserList += " , "+dr[0].ToString();

Categories

Resources