Replace the list items with specific characters using lambda - c#

This will give me the list of string having "WIGS_AUTH_" in each item. Now I want to remove this part from the list items in the same expression. Or any better way to achieve this?

you can add another Select at the end
List<PermissionDto> ans = result
.Where(x => x.Contains("WIGS_AUTH_"))
.Select(x => new PermissionDto { Name = x.Replace("WIGS_AUTH_", "") })
.ToList();

you can try something like this:
result.Where(x => x.Contains("WIGS_AUTH")).Select(x => new Permision() { Name=x.Replace("WIGS_AUTH","") }).ToList();
First its filtering the result and taking items containing "WING_AUT"
now it is creating new object of PermissionDto and set name property without "WIGS_AUTH"
adding new object to list and returning back

Related

Removing items from a list where the Id is in another list

I see this questions is quite common yet none of the answers work as expected. I have a list of objects and I need to remove some of those objects when their Id is in a specified list. I tried List.RemoveAll but that just returns an integer, not the modified list. How do I get back my list, minus the removed items?
List<Target> allServers = GetTargets(Group.Id);
List<long> excludedServers = GetExcludedServers();
List<Target> patchServers = allServers
.RemoveAll(x => !excludedServers.Any(y => y.Id == x.Id));
RemoveAll modifies your existing List, it returns the number of items it removed. To get a new list without the items you can use
var newList = myList.Where(i => !excludedItems.Any(ei => ei.Id == i.Id)).ToList();
Although if your Server class has the right equality members to compare Ids, you could just write
var newList = myList.Except(servers).ToList();
Try this
List<Target> allServers = GetTargets(Group.Id);
List<long> excludedServers = GetExcludedServers();
List<Target> patchServers = allServers
.Where(x => !excludedServers.Any(y => y.Id == x.Id)).ToList();
You could do something like this
patchServers = allServers.Where(x => !excludedServers.Contains(x.id)).ToList();

Passing a list<string> into Linq

The first query returns a list of string, and I am passing them into another table to find corresponding items, but nothing happens. no error message or nothing
var classIds = _contextSpecRepo.Get(x => x.cId.Equals(cId)).Select(x => x.classNames).Distinct().ToList();
// issue happens in the following query
var classes= Repository.Get(x => x.Id.Equals(classIds)).ToList();
The call to Equals, which takes object, hides the problem: you are comparing a single Id to a list of Ids, rather than checking if the Id is present in a collection. This compiles, but yields no result.
Here is how you can fix it:
var classes= Repository.Get(x => classIds.Any(y => y == x.Id)).ToList();
or
var classes= Repository.Get(x => classIds.Contains(x.Id)).ToList();
If you must do it in 2 queries then you have to use contains
var classes= Repository.Get(x => classIds.Contains(x.Id)).ToList();
A better solution would be to use a join on the tables.
you can also skip .ToList()
var classes= Repository.Get(x => classIds.Contains(x.Id));

LINQ Syntax for Selecting a Parameter to Be Copied

I have a some code to sort my collection in linq in C#. I want it to group by the houseName to sum over the volumes, order that collection, but also pass a third parameter, pctVol, to the new sorted collection. What am I doing wrong? I know that the problem lies in the pctVol = group.Selecct(item => item.pctVol) line.
var inBetween = this.GroupBy(item => item.houseName)
.Select(group =>
new DataItem
{
houseName = group.Key,
VOLUME = group.Sum(item => item.VOLUME),
pctVol = group.Select(item => item.pctVol)
})
.ToList();
ObservableCollection<DataItem> objSort = new ObservableCollection<DataItem>(inBetween.OrderBy(DataItem =>
DataItem.VOLUME));
return objSort;
What kind of value do you want pctVol to have? With that code, it looks like DataItem.pctVol will be an IEnumerable containing all the pctVol values in that group.
If you want a single value, and all the pctVol values in each group are guaranteed to be the same, then you could just take the value from the first element, like this: pctVol = group.First().pctVol

Get all values for a certain property name in linq?

Is there a way to get all values for a certain key in linq?
Here is my collection
[PId, Pname, EnviornementName]
So I have a collection of this type, Looking for a more generic approach, where i could check the property name and do a select. Something like,
myCollection.SelectMany(item => item).Where(item==propertyName)
how can i do this?
To get an array of named property values try
var pName = "PId";
var values = myCollection
.Select(x => x.GetType().GetProperty(pName).GetValue(x, null))
.ToArray();
There are several ways to do it, for example:
var IDs = from o in myCollection
select new { o.PId };
or
var IDs = myCollection.Select(o => o.PId);
I suggest that you start with some linq tutorial: http://www.tutorialspoint.com/linq/
using System.Linq;
MyCollection.Select(x => x.Pid).ToArray();
Or to get unique values
MyCollection.Select(x => x.Pid).Distinct().ToArray();
Or better yet, a sorted array of unique values
MyCollection
.OrderBy(x => x.Pid)
.Select(x = x.Pid)
.Distinct()
.ToArray();

best way to receive a list of objects from list of KeyValuePair?

I have a list of KeyValuePairs and I want to filter it based on the key value so eventually I will get a list of values which is filtered (meaning - will not contain all the values that were in the original list).
I guess maybe the best way is some form of Lambda expression but I am not sure how to achieve it.
Thanks,
Alon
Try this:
var values = list.Where(x => x.Key == "whatever").Select(x => x.Value);
This will give you a filtered list of the values only.
Obviously you can change the way you filter your keys.
Use the following:
var filteredList = list.Where(x => x.Key == "Key");
What you're looking for some combination of LINQ extension methods (which depends on what you're exactly trying to do).
For example if I had a List of fruits to their colors and wanted to get a collection of which fruits are red, I would do something like:
var fruits = new List<KeyValuePair<string,string>>() {
new KeyValuePair<string,string>("Apple", "Green"),
new KeyValuePair<string,string>("Orange", "Orange"),
new KeyValuePair<string,string>("Strawberry", "Red"),
new KeyValuePair<string,string>("Cherry", "Red")
};
var redFruits = fruits.Where(kvp => kvp.Value == "Red").Select(kvp => kvp.Key);
// this would result in a IEnumberable<string> { "Strawberry", "Cherry" }

Categories