Is there any difference between sql linq [duplicate] - c#

This question already has answers here:
Difference between Query Expression and Method Expression in LINQ?
(5 answers)
Closed 7 years ago.
I have a list of Pieces. I want an int[] of PieceID;
I try this, but this create an anonymous type[].
PiecesTop1 = new List<Piece>();
var test = PiecesTop1.Select(x => new {x.PieceID}).ToArray();
Then I found this syntaxis and works ok.
var lstPieceID = from p in PiecesTop1
select p.PieceID;
int[] arrPieceID = lstPieceID.ToArray();
int i = arrPieceID[0];
I usually use first sintaxis so not familiar with second one.
First question: How I make first sql to return an int[].
Second question: How can I call each of those sql query type to difference beetween them?
Is there any diference on what sintaxis should I use (just in case I'm not using any database).

var test = PiecesTop1.Select(x => x.PieceID).ToArray();

Related

Using Find() with conditional that have the first letter "AA" in c# [duplicate]

This question already has answers here:
How to check if a word starts with a given character?
(7 answers)
Closed 2 years ago.
it is possible to find some data by using this condition "that have the first letter A"
here is how i use find() to find id_cart that equal with the input
var store = await _cartCollection.Find(x => x.id_cart == entity.id_cart).ToListAsync();
but i want to change it to be like this, but i dont know how
string key = "ID";
var store = await _cartCollection.Find(x => x.id_cart "that have the first character" key).ToListAsync();
is it possible ? how should i do it ?
You can use .StartsWith(),
string key = "ID";
var store = await _cartCollection.Find(x => x.id_cart.StartsWith(key)).ToListAsync();
In c# and .Net there is a method called StartsWith() which returns a boolean.
Source docks: https://learn.microsoft.com/it-it/dotnet/api/system.string.startswith?view=net-5.0
var store = await _cartCollection.Find(x => x.id_cart.StartsWith(key)).ToListAsync();
If you want to ignore case sensitive just use StringComparer.InvariantCultureIgnoreCase
I usually use the Where() just because it's similar to SQL statement and more readable. Hope it solves.

Use Like in Linq query EF Core [duplicate]

This question already has answers here:
Like Operator in Entity Framework?
(9 answers)
Closed 3 years ago.
I have the below method in the EF Core application
public List<Prj_Detail> GetByOrg(string org)
{
var data = _context.Prj_Details.Where(w => w.Account_Name == org).ToList();
return data;
}
Here instead of == I need to check for Like how can I do that in my method
Like others have said you can do a Contains operator however in some cases this casues an unncessary TSQL casting. Instead you could use the in-built Entity Framework functions like so:
_context.Prj_Details.Where(EF.Functions.Like(w.Account_Name, org)).ToList();
Have you tried using Contains?
var data = _context.Prj_Details.Where(w => w.Account_Name.Contains(org)).ToList();
You can use StartsWith and EndsWith too.
Here's more information about it.
Could try with Contains to filter.
Please refer the below code.
depending on LeftRim/RightTrim/upperCase/LowerCase
public List<Prj_Detail> GetByOrg(string org)
{
var data = _context.Prj_Details.Where(w => w.Account_Name.Contains(org)).ToList();
return data;
}

sort list using property variable [duplicate]

This question already has answers here:
How can I do an OrderBy with a dynamic string parameter?
(11 answers)
Closed 7 years ago.
Suppose I have this list of process or any other object
List<Process> listProcess = new List<Process>();
I can sort it using this line listProcess.OrderBy(p => p.Id);
But what if I have only string name of property obtained in runtime. I assume, I should use reflection to get the property object. Can I use orderby method or I should use Sort and then pass own comparer?
You can have a look at the post referred in the comment. Or, you can achieve that using simple reflection like this
var sortedList = list.OrderBy(o => o.GetType().GetProperty(propName).GetValue(o));
Where
List<object> list; //a list of any object(s)
string propName; //name of the property to be used in OrderBy

Dynamic table name in linq [duplicate]

This question already has answers here:
Querying data using Entity Framework from dynamically created table
(2 answers)
Dynamically set the table name in LINQ query
(3 answers)
Closed 8 years ago.
I'm trying to execute some LINQ commands using a dynamic table name. For example, instead of:
var o = (from x in context.users select x);
I want to use something like:
var o = (from x in getTableObjectByName("users", context) select x);
More or less. Here's the code I have so far, which both compiles and runs:
using (MySiteEntities ipe2 = new MySiteEntities()) {
var propinfo1 = Type.GetType("MySiteNamespace.MySiteEntities").GetProperty("users");
var propval1 = propinfo1.GetValue(ipe2, null);
}
That runs, but always returns zero records. The users table most definitely contains records, and in any case when I call it directly using the first method above I get all of the records as expected. How can I modify my code to actually pull down records, rather than just an empty collection?
Edit: I've also tried this:
using (MySiteEntities ipe = new MySiteEntities())
{
var prop = Type.GetType("MySiteNamespace.MySiteEntities").GetProperty("users");
Type dbsetType = typeof(DbSet<>);
dbsetType = dbsetType.MakeGenericType(Type.GetType("MySiteNamespace.user"));
Type t = dbsetType.GetType();
var val = prop.GetValue(ipe, null);
}
In this case, the code not only runs, but actually returns the results as expected. However, val is an Object. I need to cast it to the type DbSet<user>, which would be easy enough, except that the parameter user is only known at runtime....the cast needs to be dynamic as well. I've tried using Convert.ChangeType(val, t);, but that throws an
InvalidCastException (Object must implement IConvertible).
How can I convert the val variable to an actually usable object?
No idea if this is relevant, but this is on EntityFramework 4.
In your DbContext class, add a method say called Set that returns:
public DbSet Set(string name)
{
// you may need to fill in the namespace of your context
return base.Set(Type.GetType(name));
}
Which you can query like this:
using (var db = new YourDataContext())
{
// Since your DbSet isn't generic, you can can't use this:
// db.Set("Namespace.EntityName").AsQueryable().Where(a=> a.HasSomeValue...
// Your queries should also be string based.
// Use the System.Linq.Dynamic nuget package/namespace
var results = db.Set("Namespace.EntityName")
.AsQueryable()
.Where("SomeProperty > #1 and SomeThing < #2", aValue, anotherValue);
// you can now iterate over the results collection of objects
}
More information on System.Linq.Dynamic can be found here

Determine if two collections share at least one element [duplicate]

This question already has an answer here:
Check for any element that exists in two collections
(1 answer)
Closed 9 years ago.
Is there a way to determine if a collection contains at least one element from another collection?
You can use the Any().
var listA = new List<int>();
var listB = new List<int>();
bool hasCommonItem = listA.Any(i => listB.Contains(i));
Moreover, you can write an IEqualityComparer implementation to pass it as a parameter to the Contains() if necessary.
Sure there is.
var sourceCollection = GetSourceCollection();
var otherCollection = GetAnotherCollection();
var hasAtLeastOne = sourceCollection.Intersect(sourceCollection).Any();
I assumed your collections are of the same type: IEnumerable<T> with the same T generic parameter.
It's gonna load whole sourceCollection first, and then fetch one element at a time from otherCollection until first common one is found.
col1.Any(x => col2.Any(y => x==y));

Categories