this not work
string[] DATE_Group = { "2020", "2021" }; //changing values
var query = _context.c10
.Where(u => DATE_Group.Any(s => u.ON_DATE.Contains(s)))
.ToList()
.Select(u => new
{
User_NumberID = u.User_NumberID.ToString(),
}).ToList();
I use this u.ON_DATE.Contains("2020") and work but not list or array only one value
in sql SELECT * from C10 where ON_DATE like '%2020%' or ON_DATE like '%2021%'
and in ON_DATE column content like this 1-3-2023 1-1-2021 5-1-2020
this error when used
enter image description here
Use this below code for your linq where statement.
var myVar=context.Students.where(x=>x.Name.Contains("John")).SingleOrDefault();
I think this is a better way to get the data:
var from = new DateTime(2020,1,1);
var to = new DateTime(2022,1,1);
var query = _context.c10
.Where(u => u.ON_DATE > from && u.ON_DATE < to )
...
EF Core cannot use Any with local collections (with small excpetion), only Contains is supported.
I would suggest to use function FilterByItems. And use in query:
string[] DATE_Group = { "2020", "2021" }; //changing values
var query = _context.c10
.FilterByItems(DATE_Group, (u, s) => u.ON_DATE.Contains(s), true)
.Select(u => new
{
User_NumberID = u.User_NumberID.ToString()
})
.ToList();
Related
I want to select all pictures and calculate IsAnnotated field, but how I can select * fields and apply this IsAnnotated field?
Because in this example for now only selected IsAnnotated. Do we have a possibility to prevent manually write something like Id = picture.Id, title = picture.Title?
var picture = await _dbContext.Pictures
.Select(picture => new Picture
{
IsAnnotated = _dbContext.Annotations.Any(x => x.PictureId == picture.Id),
})
.Where(s => ids.Contains(s.Id))
.ToListAsync();
First, select the Pictures you want by ids list:
var pictures = _dbContext.Pictures
.Where(s => ids.Contains(s.Id));
Second, calculate the IsAnnotated field with foreach - this is not a case of 'select', this is an update case. (Convert to 'List' for using the ForEach linq function, you can use the foreach statement instead):
pictures.ToList().ForEach(a => a.IsAnnotated = _dbContext.Annotations.Any(x => x.PictureId == a.Id));
You can do something like this.
Var pictures = _dbcontext.Pictures.Where(x=> IDs.Contains(x.id));
var annotations = await pictures.Join(_dbContext.annotation, pic => pic.id, ann => ann.pictureId, (pic, ann) => new
{
Annotation = ann.IsAnnotated
}.ToListAsync();
Or instead an anonymous type you can pass a model if you want.
Sorry if it's not readable but I wrote it from my phone!! 🙏
I have a Dictionary:
var dict = new Dictionary<int, string>();
With this values:
[0]: {[1, "Person1"]}
[1]: {[2, "Person2, Person3"]}
[2]: {[3, "Person4"]}
[3]: {[4, "Person5"]}
And when i use a "foreach" to get the values with "id" 2 i get as result "Person2, Person3".
foreach (var test in dict)
{
if (test.Key == 2)
System.Diagnostics.Debug.WriteLine(test.Value);
}
But when i use this LINQ line:
Person = dict.FirstOrDefault(q => q.Key == s.Person.ID).Value.ToString(),
I get this error:
Local sequence cannot be used in LINQ to SQL implementations of query
operators except the Contains operator.
I tried several things but nothing seems to work, so any ideas?
EDIT
I use this to show output on my page:
DataSelectionQuery = p => new
{
p.ID,
p.FirstName,
p.LastName,
TEST = dict.FirstOrDefault(q => q.Key == p.ID).Value.ToString(),
};
public Expression<Func<LinqClass, object>> DataSelectionQuery { get; set; }
And here is where it trows the error:
var results = query.Select(DataSelectionQuery).ToList();
You cannot use this kind of expressions inside Linq to SQL as they cannot be translated to SQL query
Use .ToList() at the end of your query, then use Linq to objects to complete your entity with values from Dictionary
For example when you have code like:
var result = from x in table
select new Entity
{
Id = x.Id,
Sth = x.Sth,
Person = dict.FirstOrDefault(q => q.Key == s.Person.ID).Value.ToString()
};
You need to change it to something like this:
var result = (from x in table
select new { x.Id, x.Sth, x.PersonId }) // LINQ To SQL part
.ToList() // get query results
.Select(x => new Entity
{
Id = x.Id,
Sth = x.Sth,
Person = dict.FirstOrDefault(q => q.Key == x.PersonId).Value.ToString()
}; // this part will be executed with Linq to objects
Please provide the full source code if you need more detailed help
Ok, so your "SelectionQuery" needs to be simple enough to translate into SQL query and should look like this:
DataSelectionQuery = p => new
{
p.ID,
p.FirstName,
p.LastName
};
And the other part should look like this:
var results = query.Select(DataSelectionQuery).ToList()
.Select(p => new
{
p.ID,
p.FirstName,
p.LastName,
TEST = dict.FirstOrDefault(q => q.Key == p.ID).Value.ToString()
});
Alernatively you can create your own class which will contain the Dictionary and will translate the ID into TEST on the getter action
This is how I solved the problem:
Person = string.Join(", ", PersonsQuery.Where(q => q.ID == s.ID).Select(q => q.PersonInformation))
I wrote some entity framework select:
var query = context.MyTable
.Select(a => new
{
count = a.OtherTable.Where(b => b.id == id).Sum(c => c.value),
total = a.OtherTable2.Where(d => d.id == id) * count ...
});
I have always select total:
var query = context.MyTable
.Select(a => new
{
count = a.OtherTable.Where(b => b.id == id).Sum(c => c.value),
total = a.OtherTable2.Where(d => d.id == id) * a.OtherTable.Where(b => b.id == id).Sum(c => c.value)
});
Is it possible to select it like in my first example, because I have already retrieved the value (and how to do that) or should I select it again?
One possible approach is to use two successive selects:
var query = context.MyTable
.Select(a => new
{
count = a.OtherTable.Where(b => b.id == id).Sum(c => c.value),
total = a.OtherTable2.Where(d => d.id == id)
})
.Select(x => new
{
count = x.count,
total = x.total * x.count
};
You would simple do
var listFromDatabase = context.MyTable;
var query1 = listFromDatabase.Select(a => // do something );
var query2 = listFromDatabase.Select(a => // do something );
Although to be fair, Select requires you to return some information, and you aren't, you're somewhere getting count & total and setting their values. If you want to do that, i would advise:
var listFromDatabase = context.MyTable.ToList();
listFromDatabase.ForEach(x =>
{
count = do_some_counting;
total = do_some_totalling;
});
Note, the ToList() function stops it from being IQueryable and transforms it to a solid list, also the List object allows the Linq ForEach.
If you're going to do complex stuff inside the Select I would always do:
context.MyTable.AsEnumerable()
Because that way you're not trying to still Query from the database.
So to recap: for the top part, my point is get all the table contents into variables, use ToList() to get actual results (do a workload). Second if trying to do it from a straight Query use AsEnumerable to allow more complex functions to be used inside the Select
I need to join multiple criteria inside a linq query, I have a criteria box like below :
Currently Im using a query than can only handle a single tag :
var c = *text after the t:*
var r = rs.Returns.Where(x => x.Lines.Any(y => y.Tags.Any(z => z.Name.Contains(c))));
I need something like (this may be incorrect) :
var r = rs.Returns.Where(x => x.Lines.Any(y => y.Tags.Any(z => z.Name.Contains(*1st Tag*)) && y.Tags.Any(z.Name.Contains(*2nd Tag*)))); .. etc
So that all the tags the Line has are searched and AND is applied. Is there an easy way of achieving such a thing?
Many thanks in advance.
var r = rs.Returns.Where(x => x.Lines.Any(y => searchTags.All(stag => y.Tags.Any(z => z.Name.Contains(stag)))));
searchTags should contain all tags to search for. No need to use a loop.
I think you are looking for something like this:
List<string> tags = new List<string>() { "tag1", "tag2" };
var query = rs.Returns.AsEnumerable();
foreach(string tag in tags)
{
string tmp = tag;
query = query.Where(x => x.Lines.Any(y => y.Tags.Any(z => z.Name.Contains(tmp))));
}
How to Put the following query result into a List
var result = from c in sb.Swithches_SW_PanalComponents
select new { c.ID,c.SW_PanalComponents.ComponentsName,c.ComponentValue };
FINAL EDIT
Based on your last comment, this is all you ever needed
List<Swithches_SW_PanalComponents> result =
sb.Swithches_SW_PanalComponents.ToList();
which of course is identical to
var result = sb.Swithches_SW_PanalComponents.ToList();
EDIT
Based on your comments, I think this is what you want:
List<SW_PanalComponents> result = sb.Swithches_SW_PanalComponents
.Select(c => new SW_PanalComponents { /* initialize your fields */ })
.ToList();
END EDIT
The ToList method is what you want. But consider using dot notation. For simple queries like this, it's much cleaner and trimmer.
var result = sb.Swithches_SW_PanalComponents
.Select(c => new { c.ID, c.SW_PanalComponents.ComponentsName, c.ComponentValue })
.ToList();
Also note that, if you're just trying to execute your query immediately, and only need to enumerate over it, you can also call AsEnumerable()
var result = sb.Swithches_SW_PanalComponents
.Select(c => new { c.ID, c.SW_PanalComponents.ComponentsName, c.ComponentValue })
.AsEnumerable();
The advantage here is that result is a less specific type—IEnumerablt<T>.
Like this:
var result =(from c in sb.Swithches_SW_PanalComponents
select new
{ c.ID,
c.SW_PanalComponents.ComponentsName,
c.ComponentValue
}).ToList();
That what i came with finally:
List<Swithches_SW_PanalComponents> MyList = new List<Swithches_SW_PanalComponents>();
var Result = from all in sb.Swithches_SW_PanalComponents
select all
;
MyList.AddRange(Result.ToList<Swithches_SW_PanalComponents>());