Removing items in List using LINQ [duplicate] - c#

This question already has answers here:
Using LINQ to remove elements from a List<T>
(14 answers)
Closed 9 years ago.
I have a List of type some entity
List
public class OrderLine
{
public string productCode;
public int quantity;
}
i need to remove items from the above List if the productCode is equal to some products.
List<string> ProductsToBeExcluded = new List<string>(){"1234","1237"};
so, from List<OrderLine> i need to remove products which are equal to 1234 and 1237
i have tried
create a List<string> from List<OrderLine> using
List<OrderLine> OrderLines = GetOrderLines();
var ol = from o in OrderLines
select o.ProductCode;
2.
List<string> ProductsToBeExcluded = new List<string>(){"1234","1237"};
var filtered = OrderLines.Except(ProductsToBeExcluded);
how do I proceed further in removing
thanks

In this case you don't need LINQ but can just use List<T>.RemoveAll instead
OrderLines.RemoveAll(x => ProductsToBeExcluded.Contains(x.ProductCode));

Use RemoveAll method of List which accepts predicate
OrderLines.RemoveAll(x => ProductsToBeExcluded.Contains(x.ProductCode));

Related

Extracting a list from a list LINQ [duplicate]

This question already has answers here:
Using LINQ, select list of objects inside another list of objects
(2 answers)
Closed 1 year ago.
I am trying to extract a list of Goals from within a list of Students using this method
public List<Goal> GetGoalsForTeacher(int userId)
{
var students = GetStudentsForTeacher(userId);
var result = students.Select(e => e.Goals).ToList();
return result
}
However, I need it to return a List, but it is returning a List<IList>. Has anyone any idea on how I would convert this or make it a List initially?
You're looking for the SelectMany() method.
var result = students.SelectMany(e => e.Goals).ToList();

c# How to save duplicates from list into dictionary? [duplicate]

This question already has answers here:
Using Linq to group a list of objects into a new grouped list of list of objects
(5 answers)
Closed 4 years ago.
I got list of Issues,
Where Issue
public class Issue
{
public string version{ get; set; }
public string someDescription { get; set; }
}
versions are duplicated e.g:
List<
{"1.2.8", value1},
{"1.3.1", value2},
{"1.2.8", value3}
>
and I need to split duplicates into dictionary, where key is a specific verison, and value is a list of values like:
Dictionary<stirng, List<string>> duplicates;
what mean Dictionary<EachVersion, List<valuesForThisVersion>>
got something like this:
var VerisonList = records.GroupBy(r => r.Verison).Select(w=>w.Key).ToList();
this give me a list of versions, but have no idea how to fast get list of values where verison == VerisonList.element;
Is it possible with one linq?
EDIT: This is NOT a duplicate of the other question. In linked post there is no answer for my problem!!
Sure, using ToDictionary():
records.GroupBy(r => r.Verison)
.ToDictionary(g => g.Key,
g => g.Select(i => i.someDescription).ToList());

Remove Duplicates from dropdown using Linq [duplicate]

This question already has answers here:
Distinct not working with LINQ to Objects [duplicate]
(11 answers)
Closed 7 years ago.
I have a list of books, each book has a author assigned to it.
What I'm trying to do is allow the user the filter the results based on the author.
So some books may have the same Author etc but I want to filter the Authors out only show and entry for each one in my dropdown.
This is what I currently have :
var bookAuthors = Cache.CacheExtension.GetFromCache<List<BookCollection>>("books"); // Returns me the collection of books
// Filter the Authors out of the books
var authorCollection = bookAuthors.DistinctBy(item => new Options { Id = item.BookAuthor.ToString(), Description = item.BookAuthor }).ToList(); // Doesn't remove duplicates
As you can see I'm using DistinctBy but nothing gets filtered.
If I do this
var authorCollection = bookAuthors.Select(item => new Options { Id = item.BookAuthor.ToString(), Description = item.BookAuthor }).ToList(); // I get a list of Authors.
I get the list but it contains duplicates, any help would be grand
Use GroupBy() in Linq
var distinctItems = authorCollection.GroupBy(x => x.Id).Select(y => y.First());

Linq Select All Items Matching Array

I have a data collection of type IEnumerable<Objects.LabourHours> containing labour records for various employees. I wish to filter the list and return only records for selected employees, which is specified by a list of int[] employees containing the EmployeeIDs.
class LabourHours
{
public int ID {get;set;}
public int EmployeeID {get;set;}
public int HoursWorked {get;set;}
}
How would I go about this? I am sure this has been asked before but I can't find anything similar on here. The closest I have found involves grouping the records by UserID, which is not what I need - I need the actual records.
You can filter your list with LINQ Where using Contains method:
var result = list.Where(x => employees.Contains(x.EmployeeID));
If you want the result to preserve the order of the employees array, you can use Select on the array. From the doc, it "Projects each element of a sequence into a new form", which is basically what you'd want to do in this case.
var result = employees.Select(e => labourHours.First(l => l.EmployeeID == e));
Use FirstOrDefault if all employees don't necessarily have an associated labourHours entry.

LINQ Multiple order by when not using lambda expressions [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Multiple “order by” in LINQ
I want to order some dataset by some field AND THEN some other field.
Using lambda expressions this would be easy (OrderBy.ThenBy), but how to do it when I have a syntax like this:
int maxQueries = int.MaxValue;
// finds the most search for queries
var ordered = from p in searchLogs
where !string.IsNullOrEmpty(p.SearchQuery)
group p by new
{
SearchQuery = p.SearchQuery
}
into pgroup
let count = pgroup.Count()
orderby count descending
select new
{
Count = count,
SearchQuery = pgroup.Key.SearchQuery
};
I can't seem to find a way which works after the decending keyword (like orderby count descending then searchquery)..
Any ideas?
Put a comma after descending and specify the next thing to sort by (optionally adding descending) and so on
Just to add some code to mlorbetske answer, if you have Customer class like this:
public class Customer
{
public string Name;
public DateTime MemberSince;
}
You could then perform an ordering like this:
var q = from c in Customers
orderby c.MemberSince.Date descending, c.Name
select c;

Categories