Determine if LINQ Enumerable contains object based on a condition? [duplicate] - c#

This question already has answers here:
Linq Contains method for a object
(4 answers)
Closed 10 years ago.
I have an IEnumerable<Project>
I want to know if this list has any element Project.ID == someID.
Is there a way to do that?

Yes, you want to use the Any method (documentation).
IEnumerable<Project> projects = SomeMethodReturningProjects();
if(projects.Any(p => p.ID == someID))
{
//Do something...
}

You can use the Any() extension method.
var hasAny = projectList.Any(proj => proj.ID == someID);
Or, if you want to get that record, you can use FirstOrDefault():
var matchedProject = projectList.FirstOrDefault(proj => proj.ID == someID);
This will return null if it finds nothing that matches, but will pull the whole object if it does find it.

Using
projects.Any(p => p.ID == someID)
returns true (a boolean) if the predicate matched for any element.

Yes, use the Any extension method:
list.Any(p => p.ID == someID);

Related

Check if object with specific value exists in List [duplicate]

This question already has answers here:
Searching if value exists in a list of objects using Linq
(9 answers)
Closed 3 years ago.
i am trying to check if a specific object exists in a List. I have ListA, which contains all the Elements, and i have a string, which may or may not belong to the id of one object in List A.
I know the following:
List<T>.Contains(T) returns true if the element exists in the List. Problem: I have to search for a specific Element.
List<T>.Find(Predicate<T>) returns an Object if it finds an element in the List which has the predicate. Problem: This gives me an object, but i want true or false.
Now i came up with this:
if (ListA.Contains(ListA.Find(a => a.Id == stringID)) ==true) ...do cool shit
is this the best solution? Seems kind of odd to me.
You can use Any(),
Any() from Linq, finds whether any element in list satisfies given
condition or not, If satisfies then return true
if(ListA.Any(a => a.Id == stringID))
{
//Your logic goes here;
}
MSDN : Enumerable.Any Method
Using .Any is the best option: MSDN
if(ListA.Any(a => a.Id == stringID))
{
//You have your value.
}
Use Any for this.
if (ListA.Any(item => item.id == yourId))
{
...
}

Check for null after FirstOrDefault? [duplicate]

This question already has an answer here:
selecting a property from FirstOrDefault in case FirstOrDefault returns null
(1 answer)
Closed 4 years ago.
I want to find the first member of a dictionary which satisfies certain condition and then get some properties from the found item. My concern is what if no item is found. Consider this code:
Dictionary<int, Class1> dict;
....
....
var foundPair = dict.Select(i => new { i }).FirstOrDefault(somePredicate);
SomeClass result = null;
if (foundPair != null)
result = foundPair.i.Value.SomeProp;
The result is what I'm looking for and this code looks obscure to me. Can we get the above functionality in a single linq chain? I mean something similar to this:
var result = protsDict.Select(i => new { i }).FirstOrDefault(somePredicate).SomeLinqChain(...).i.Value.SomeProps;
And the result should be SomeProps if an item is found and null if no item is found.
It could be rewritten, in various ways, as:
The key is: use Where
var result = protsDict.Where(somePredicate).SomeLinqChain(...) //some chain
.Where(someMore) //some more
.Where(i => i.Value != null) //or even...
.Select(i =>i.Value.SomeProps).FirstOrDefault();//then select; take or skip
You can use Where followed by Take(1) to isolate at most one element which satisfies the condition.
var foundPair = dict
.Select(i => new { i })
.Where(somePredicate)
.Take(1)
.Select(x => some_mapping(x)
...;
When done this way, the subsequent expressions will only be executed if the first element satisfying the predicate has been found, and only on that element. Should more elements satisfy the predicate, all but the first one would be ignored.
In that sense, this technique works the same as FirstOrDefault, only in a safe way.

Entity Framework include items only by condition [duplicate]

This question already has answers here:
EF: Include with where clause [duplicate]
(5 answers)
Closed 6 years ago.
I need my context to include the sonns by a condition, I need the rows that not deleted (logical delete).
I understood that I cannot add a condition to the include; so I want to filter the context, but it's not working.
var aa = ctx.aa
.Include(t => t.vari)
.ToList()
.FirstOrDefault();
ctx.vari.Where(bi => bi.ID == 10 && bi.Deleted == 1).ToList();
Thanks!
As codelahiru && hbulens pointed out, you missed the bi for ID.
Disclaimer: I'm the owner of the project Entity Framework Plus
The Query IncludeOptimized feature allows to filter with include and optimize the query performance at the same time (Support EF5, EF6)
var aa = ctx.aa
.IncludeOptimized(t => t.vari.Where(bi => bi.ID == 10 && bi.Deleted == 1))
.FirstOrDefault();
Documentation: EF+ Query IncludeOptimized
This isn't going to be the most performant query. It would be better to drop the ToList()
var aa = ctx.aa.Include(t => t.vari).ToList().FirstOrDefault();
// You missed the variable before ID
ctx.vari.Where(bi => bi.ID == 10 && bi.Deleted == 1).ToList();

Design: List storing objects; access information associated with that object [duplicate]

This question already has answers here:
Linq Contains method for a object
(4 answers)
Determine if LINQ Enumerable contains object based on a condition? [duplicate]
(4 answers)
Closed 10 years ago.
I have two classes that are pertinent to what I'm trying to do.
Class 1: Person
Class 2: Personal Profiles
Person has properties such as address, name, phone #, etc...
Inside of my Personal Profiles class I have a List that stores the information for the Person's that have been created.
My question: If I'm trying to find out whether a Person with address: 999 Candy Lane exists within the List do I need to create a a new Person with default's for everything except the specified address and then use that in my .Exists or .Contains? Or should I not be creating a new object just for a searching function.
Why don't you use Linq:
theList.Where(x => x.address == "999 Candy Lane").First();
If you use .net 3.5+ you can use a linq query:
i.e.
var result = (from p in Profiles where p.Address=="bla bla" select p).FirstOrDefault();
The result will be null if no matching person is found.
Given the high probability of missing values it is better to use FirstOrDefault.
Of course First and FirstOrDefault takes a predicate so there is no need to use Where
var result = List.FirstOrDefault(x => x.Address == "999 Candy Lane");
if(result != null)
{
......
}
This is the exact use case for Any.
It is used like this:
if(People.Any(p => p.Address.Equals("999 Candy Lane")))
{
//.....
}
No you don't have to create a new object for searching:
Person person = profiles.PersonsList.Where(p => p.Address == "Address here")
.Select(p => p);
You probably want to use linq and a lambda:
var candyLane = Persons.Where(x => x.Address == "999 Candy Lane").ToList();
What this does is supply a lambda predicate to be used as a selector. Think of it like an anonymous function specified like this:
public bool CandyLaneChecker(x){
return x.Address == "999 Candy Lane";
}
Where the braces and return keyword are replaced by a => and the public bool CandyLaneChecker is omitted because this is an anonymous function. That would leave (x) => x.Address == "999 Candy Lane" and we could've left the parenthesis in our original predicate, but they're not needed.
Alternately, one could use a linq expression such as:
var candyLane = (from p in persons
where p.Profile.Address == "999 Candy Lane"
select p).ToList();
Which looks a lot more like a database query and is easier for some people to understand.
The great part about the linq expression is that you could even use that same expression with XML.

how to select an item from generic list by linq

I have a LINQ query which contains a method GetInstanceForDatabase()
principlesList.Select(p => p.GetInstanceForDatabase()).ToList()
where
List<PrincipleInstance>() principlesList = ...
// (contains list of principle like "Manual Trades", "OPM", "Flora")
GetInstanceForDatabase() is a method which takes all other info about a principle (like manual trades).
My problem is that I want to sort out only principle like only "Manual Trades".
I want to put a where clause. I tried but it is fails.
To get a single item use:
query.First(x => x.property == "Manual Trades");
// or
query.FirstOrDefault(x => x.property == "Manual Trades");
var list = p.GetInstanceForDatabase().where(x => x.propertyName == "Manual Trades").ToList();
I'm sure you're GetInstanceForDatabase needs to return your collection that you then filter for the 'Manual Trades' but I can't really tell how you get your list of PrincipalInstances from the question.
This is the correct syntax of using Where in LINQ
principlesList.Select(p => p.GetInstanceForDatabase()).Where(p => p.SomeProperty == "SomeValue").ToList();

Categories