I am trying to figure out non query way to do return a list of all objects if their ID is in test list. Example below:
Hero - table
Columns: id = INT , name = STRING, age = INT, power = INT;
var testList = {1,2,3};
var secondArray = {};
foreach (var id in testList )
{
// check if ID in database
var item = db.Hero.ToList().Find(o => o.Id = id);
if( item != null)
{
secondArray.push(item);
}
}
Now i have seen this whole thing done in single line but cannot remember how it was done.
The result i am after is List of all objects containing that have ids 1,2,3.
You have to use Contains on testList:
var secondArray= db.Hero.Where (h=> testList.Contains(h.Id))
How about
var result = db.Hero.Where(x => testList.Contains(x.Id));
This would hit DB just once instead of 3 times.
Related
I have this class:
public class RecipeLine
{
public List<string> PossibleNames { get; set; }
public string Name { get; set; }
public int Index { get; set; }
}
I have a list of multiple RecipeLine objects. For example, one of them looks like this:
Name: apple
PossibleNames: {red delicious, yellow delicious, ... }
Index = 3
I also have a table in my db which is called tblFruit and has 2 columns: name and id. the id isn't the same as the index in the class.
What I want to do is this:
for the whole list of RecipeLine objects, find all the records in tblFruit whose name is in PossibleNames, and give me back the index of the class and the id in the table. So we have a list in a list (a list of RecipeLine objects who have a list of strings). How can I do this with Linq in c#?
I'm pretty sure there isn't going to be a LINQ statement that you can construct for this that will create a SQL query to get the data exactly how you want. Assuming tblFruit doesn't have too much data, pull down the whole table and process it in memory with something like...
var result = tblFruitList.Select((f) => new {Id = f.id, Index = recipeLineList.Where((r) => r.PossibleNames.Contains(f.name)).Select((r) => r.Index).FirstOrDefault()});
Keeping in mind that Index will be 0 if there isn't a recipeLine with the tblFruit's name in it's PossibleNames list.
A more readable method that doesn't one-line it into a nasty linq statement is...
Class ResultItem {
int Index {get;set;}
int Id {get;set;}
}
IEnumerable<ResultItem> GetRecipeFruitList(IEnumerable<FruitItem> tblFruitList, IEnumerable<RecipeLine> recipeLineList) {
var result = new List<ResultItem>();
foreach (FruitItem fruitItem in tblFruitList) {
var match = recipeLineList.FirstOrDefault((r) => r.PossibleNames.Contains(fruitItem.Name));
if (match != null) {
result.Add(new ResultItem() {Index = match.Index, Id = fruitItem.Id});
}
}
return result;
}
If tblFruit has a lot of data you can try and pull down only those items that have a name in the RecipeLine list's of PossibleName lists with something like...
var allNames = recipeLineList.SelectMany((r) => r.PossibleNames).Distinct();
var tblFruitList = DbContext.tblFruit.Where((f) => allNames.Contains(f.Name));
To get all the fruits within your table whose Name is in PossibleNames use the following:
var query = myData.Where(x => myRecipeLines.SelectMany(y => y.PossibleNames).Contains(x.Name));
I don't think you can do this in a single step.
I would first create a map of the possible names to indexes:
var possibleNameToIndexMap = recipes
.SelectMany(r => r.PossibleNames.Select(possibleName => new { Index = r.Index, PossbileName = possibleName }))
.ToDictionary(x => x.PossbileName, x => x.Index);
Then, I would retrieve the matching names from the table:
var matchingNamesFromTable = TblFruits
.Where(fruit => possibleNameToIndexMap.Keys.Contains(fruit.Name))
.Select(fruit => fruit.Name);
Then you can use the names retrieved from the tables as keys into your original map:
var result = matchingNamesFromTable
.Select(name => new { Name = name, Index = possibleNameToIndexMap[name]});
Not fancy, but it should be easy to read and maintain.
I would like to create an anonymous type from linq. Then change the value of a single property(status) manually and give the list to a repeater as data source. But doesn't let me do that as theay are read-only. Any suggestion?
var list = from c in db.Mesai
join s in db.MesaiTip on c.mesaiTipID equals s.ID
where c.iseAlimID == iseAlimID
select new
{
tarih = c.mesaiTarih,
mesaiTip = s.ad,
mesaiBaslangic = c.mesaiBaslangic,
mesaiBitis = c.mesaiBitis,
sure = c.sure,
condition = c.onaylandiMi,
status = c.status
};
foreach (var item in list)
{
if (item.condition==null)
{
item.status == "Not Confirmed";
}
}
rpCalisanMesai.DataSource = list.ToList();
rpCalisanMesai.DataBind();
Instead of trying to change the value after creating the list, just set the right value while creating the list.
var list = from c in db.Mesai
join s in db.MesaiTip on c.mesaiTipID equals s.ID
where c.iseAlimID == iseAlimID
select new
{
tarih = c.mesaiTarih,
mesaiTip = s.ad,
mesaiBaslangic = c.mesaiBaslangic,
mesaiBitis = c.mesaiBitis,
sure = c.sure,
condition = c.onaylandiMi,
status = c.onaylandiMi != null ? c.status : "Not Confirmed"
};
Also, if you could change the property, your problem would be executing the query twice: first in the foreach-loop, and then again by calling list.ToList() (which would create new instances of the anonymous type).
You cannot, anonymous type's properties are read-only.
You need to set it during object creation. See #Dominic answer for code sample.
You can. For instance:
var data = (from a in db.Mesai select new { ... status = new List<string>() .. }).ToList();
Next, compute your status:
foreach (var item in data) {
item.status.Add("My computed status");
}
And then on rendering:
foreach (var item data) {
Response.Write(item.status[0]);
}
EDIT: The list can even be intialized as per your requirement:
var data = (from a in db.Mesai select new { ... status = new List<string>(new
string[] { c.status }) .. }).ToList();
foreach (var item in data) {
item.status[0] = "My computed status";
}
EDIT2: Seems like you must initialize the list, preferably with e.g. c.rowid.ToString(), otherwise the optimizer assigns the same new List() to all items, thinking that this might be some game or something.
I am working on a collection. I need to remove one item from a collection and use the filtered/removed collection.
Here is my code
public class Emp{
public int Id{get;set;}
public string Name{get;set;}
}
List<Emp> empList=new List<Emp>();
Emp emp1=new Emp{Id=1, Name="Murali";}
Emp emp2=new Emp{Id=2, Name="Jon";}
empList.Add(emp1);
empList.Add(emp2);
//Now i want to remove emp2 from collection and bind it to grid.
var item=empList.Find(l => l.Id== 2);
empList.Remove(item);
The issue is even after removing the item my collection still shows count 2.
What could be the issue?
EDIT:
Original Code
var Subset = otherEmpList.FindAll(r => r.Name=="Murali");
if (Subset != null && Subset.Count > 0)
{
foreach (Empl remidateItem in Subset )
{
Emp removeItem = orginalEmpList.Find(l => l.Id==
remidateItem.Id);
if (removeItem != null)
{
orginalEmpList.Remove(remidateItem); // issue here
}
}
}
It is working fine. In actual code i was removing remediateItem. remediateItem was
same type but it belongs to different collection.
You are passing the objects to Remove which are not in your list you are trying to remove but copy of your object in other the list, that is why they are not being deleted, Use List.RemoveAll method to pass the predicate.
lst.RemoveAll(l => l.Id== 2);
If you want to remove many ids in some other collections like array of ids
int []ids = new int[3] {1,3,7};
lst.RemoveAll(l => ids.Contains(l.Id))
int removeIndex = list.FindIndex(l => e.Id== 2);
if( removeIndex != -1 )
{
list.RemoveAt(removeIndex);
}
Try this may be work for you
This original code you have pasted, works perfectly. its removing the items accordingly.
List<Emp> empList = new List<Emp>();
Emp emp1 = new Emp { Id = 1, Name = "Murali" };
Emp emp2 = new Emp { Id = 2, Name = "Jon" };
empList.Add(emp1);
empList.Add(emp2);
//Now i want to remove emp2 from collection and bind it to grid.
var item = empList.Find(l => l.Id == 2);
empList.Remove(item);
You wrote your lambda wrong. It should be this way
var item=empList.Find(l => l.Id== 2);
You need to add this blow the menthod Remove():
orginalEmpList.SaveChanges();
I have 2 tables: winery and wineType (in wineType I have foreign key for winery, called wineryID). I try get all winery names that produce wine like the one the client selected from drop down list. And I have this function
public void ispolniLista()
{
DataClassesDataContext MyDB = new DataClassesDataContext();
var id = from wineT in MyDB.WineTypes where wineT.kind == ddlSorti.SelectedItem.Text select new { wineT.wineryID };
List<int> listaID = id as List<int>;
List<string> listaIminja = new List<string>();
try
{
foreach (int i in listaID)
{
var vname = from w in MyDB.Wineries where w.wineryID == i select new { w.name };
listaIminja.Add(vname.ToString());
}
lstVinarii.DataSource = listaIminja;
lstVinarii.DataBind();
}
catch (NullReferenceException err)
{
Console.Write(err.Message);
}
}
And I have nothing for result, the lstVinarii is empty.
Where you are casting the result like this:
List<int> listaID = id as List<int>;
You need to instantiate it so the enumerable is actually enumerated, like this:
List<int> listaID = new List<int>(id);
However, it would be worth re-writing this to take advantage of joins, because you're going to be popping off a lot of queries with the method above (because you have a query within a loop).
List<int> id = ( from wineT in MyDB.WineTypes where wineT.kind == ddlSorti.SelectedItem.Text select wineT.wineryID ).ToList();
Do this !
EDIT
Note: From your code Remove new from select, no need to create extra anonymous type that is also one problem
To avoid comment error write like this
var id = from wineT in MyDB.WineTypes
where wineT.kind == ddlSorti.SelectedItem.Text
select wineT.wineryID ;
Remove new from select, no need to create extra anonymous type same in below code
try
List<int> listaID = id.ToList<int>();
than remove foreach loop and write like this
var listaIminja= (from win MyDB.Wineries
where listaID .Contains( w.wineryID )
select w.name ).ToList();
lstVinarii.DataSource = listaIminja;
lstVinarii.DataBind();
I have a List Collection and say that i am adding 3 items to them.
list.Add(new ContentDomain() { Id = "1" , Content = "aaa,bbb,ccc,ddd"});
list.Add(new ContentDomain() { Id = "2" , Content = "aa,bb,cc,dd"});
list.Add(new ContentDomain() { Id = "3" , Content = "a,b,c,d"});
Now what i want is to fetch the rows that have just 'a' in the Content attribute.
Like i tried something like
list = list.Where(x => x.Content.ToLower().Contains("a")).ToList();
but that would give me all the three rows.
i want to search in a string for the exact string only.
list.Where(x => x.ToString().ToLower().Split(',').Where(a => a.Trim() == "a").Any()).ToList();
edit: Changed Count() > 0 to Any() for better performance
Convert it to an array of strings, and find the string in the array.
list = list.Where(x => x.Content.ToLower().Split(',').IndexOf("a")>= 0).ToList();
Try this:
IList<ContentDomain> returned = new List<ContentDomain>();
foreach(ContentDomain myList in list)
{
var ret = myList.Content.Split(',');
bool exists = (from val in ret
where val.Contains('a')
select true).FirstOrDefault();
if (exists)
returned.Add(myList);
}