How to loop collections in LINQ and pass on data - c#

How do i do this in LINQ - So i dont have to use ForEach or loops?
I can't seem to figure out how to pass a list when some condition is met and this way loop the collection with LINQ.
products.ForEach(delegate(CustomEcomProducts p)
{
p.VariantProducts = variants.Where(prod => prod.VariantParentID == p.ProductID)
.ToList();
});

That's not what LINQ is for. The Q in LINQ stands for "Query".
The best/cleanest/most readable way to do this is the following:
foreach(var product in products)
product.VariantProducts = variants.Where(x => x.VariantParentID == p.ProductID)
.ToList();

Related

Group by clause inside a nested list

I am trying to apply group by clause to a list element inside a parent list. How can I skip looping and write this within a single linq query
foreach (var record in marketRecordDTOs)
{
record.Sources = record.Sources
.GroupBy(i => i.SourceId)
.Select(i => i.FirstOrDefault())
.ToList();
}
So you can easily create an IEnumerable<> of all your new Sources:
var newSources = marketRecordDTOs.Select(record => record.Sources
.GroupBy(i => i.SourceId)
.Select(i => i.FirstOrDefault())
.ToList()
);
Though, I am not sure what you intend to do with it after that.

Two for loops in lambda expression

How to create the exactly following two for's in lambda expression?
foreach (var item in list1)
{
foreach (var item2 in list2)
{
if (item.number == item2.number)
{
return false;
}
}
}
Since you're just checking to see if any one item matches, you can use Any().
return !list1.Any( item1 => list2.Any(item2 => item2 == item1 ));
I would just use the Intersect function available for lists and this will return you all the elements that are common in 2 lists. If you just want to see if one exists then you can do it very easily by checking the count.
int count = List1.Select(s => s.number).Intersect(List2.Select(s => s.number)).Count;
If you want to know which elements are unique in both lists then use the Exclude method.
var uniqueItems = List1.Select(s => s.number).Except(List2.Select(s => s.number));
Here you go !!
Using Linq Method Syntax :
!list1.Any(item => list2.Any(item2 => item.number == item2.number))
Using Linq Query syntax:
!(from item in list1
from item2 in list2
where item.number==item2.number select item).Any()

Linq to avoid nested foreach loop to get unique values

I have below query, but it has 2 foreach loops which i consider not good. How can i get distinct value from IEnumerable> object by using linq.
Below is the code i have written,
var floatingIds= subInfo.Ranges.Select(c => c.RangeIDs.Select(s=>s)).Distinct();
var floatIds= new List<Guid>();
foreach (var ids in floatingIds)
foreach (var id in ids)
{
if (!floatIds.Contains(id))
{
floatIds.Add(id);
}
}
I have this post, but still am not getting expected values, but the above code gives correct IDs How do I avoid using nested foreach statements by using lambda or linq in this scenario?
You can use SelectMany to flatten the collection and get all distinct values without any foreach:
var floatIds = subInfo.Ranges
.SelectMany(c => c.RangeIDs.Select(s=>s))
.Distinct()
.ToList();
var floatIds = subInfo.Ranges
.SelectMany(c => c.RangeIDs.Select(s=>s))
.Distinct()
.ToList();

c# and LINQ - convert IGrouping to List

I have the following code written to find common objects in a list of objects
https://dotnetfiddle.net/gCgNBf
..............................
var query = setOfPersons
.SelectMany(l => l.Select(l1 => l1))
.GroupBy(p => p.Id)
.Where(g => g.Count() == setOfPersons.Count);
After that, I need to convert "query" to a list of "Person" objects ( List ) to achieve something else.
I tried using "ToList()"... But it says:
" cannot convert IGrouping to a List ".
Can someone help me to fix it ?
Looking at your code it seems that what you are trying to achieve is to get the list of people that exist in each list. If so, you can use the following query:
var query = setOfPersons
.SelectMany(l => l.Select(l1 => l1))
.GroupBy(p => p.Id)
.Where(g => g.Count() == setOfPersons.Count)
.Select(x=>x.First()) // Select first person from the grouping - they all are identical
.ToList();
Console.WriteLine("These people appears in all set:");
foreach (var a in query)
{
Console.WriteLine("Id: {0} Name: {1}", a.Id, a.Name);
}
Here you select just a single item from each grouping, because they all are identical.

Can I do a EF statement Where( c => c.NameStr == (is element in list<string> ) )?

I want to do a Where statement but check to see if a field member matches an item in a list of strings instead of just a string. My entities are autogenerated from the DB and stored in the .edmx file.
//selectedAgencys is a List<string>
List<v_MapCrimeData> list = ent.v_MapCrimeData
.Where(c => c.AgencyName == (element in list selectedAgencys));
You want to see if the list contains the field, so you can use the Enumerable.Contains
nt.v_MapCrimeData.Where(c => selectedAgencys.Contains(c.AgencyName))
Since you indicated you're using Linq to Entities you might want to try a join.
List<v_MapCrimeData> list = v_MapCrimeData.Join(
selectedAgencies,
c => c.AgencyName, //key selector for v_MapCrimeData
a => a, //key selected for selectedAgencies
(c, a) => c).ToList(); //result selector (i.e. return the v_MapCrimeData)
Try
List<v_MapCrimeData> list = (from c in ent.v_MapCrimeData
from x in selectedAgencys
where x == c.AgencyName
select c).ToList();
If you need to ignore case,
nt.v_MapCrimeData.Where(c => selectedAgencys.Any(a => a.Equals (c.AgencyName, StringComparison.OrdinalIgnoreCase))
.Where(i => listocheckagainst.Contains(i.valuetoBeChecked))
Edit: spent time signing up to SO and someone else answered

Categories