Create a LINQ query comparing arrays - c#

I'm very new to LINQ and I'm searching to filter an SQL view which has a column called 'Readers' containing several group names separated by '#' (es. "Administrators#HR Group#Employees Group").
Having a list of user's groups, I need to extract all the records where Readers contains at least one of the user's groups.
In other words, the user must see only those records belonging to him.
I found this solution, but I think it's extremely inefficient:
private List<vwFax>getmyFaxes(List<string> myGroups)
{
var myFax = db.vwFax.AsQueryable();
var res = db.vwFax.AsQueryable();
List<vwFax> outRes= new List<vwFax>();
foreach (string elem in myGroups)
{
res = (from a in myFax
where a.Readers.Contains(elem)
select a);
if(res.Count() > 0)
{
outRes.AddRange(res);
}
}
return outRes.ToList();
}
Any help please?

Basically what you are saying in the following query is: For each item in myFax take it only if that item.Readers contains Any (at least 1) of the items in myGroups
outRes = db.myFax.Where(item => myGroups.Any(grp => item.Readers.Contains(grp)));
and in query-syntax:
outRes = from item in db.myFax
where myGroups.Any(grp => item.Readers.Contains(grp))
select item;

Related

How to simplify LINQ query just to filter out some special rows

I am very unfamiliar with Entity Framework and LINQ. I have a single entity set with some columns where I want to filter our some special rows.
4 of the rows are named Guid (string), Year (short), Month (short) and FileIndex (short). I want to get all rows which have the maximum FileIndex for each existing combination of Guid-Year-Month.
My current solution looks like this:
var maxFileIndexRecords = from item in context.Udps
group item by new { item.Guid, item.Year, item.Month }
into gcs
select new { gcs.Key.Guid, gcs.Key.Year, gcs.Key.Month,
gcs.OrderByDescending(x => x.FileIndex).FirstOrDefault().FileIndex };
var result = from item in context.Udps
join j in maxFileIndexRecords on
new
{
item.Guid,
item.Year,
item.Month,
item.FileIndex
}
equals
new
{
j.Guid,
j.Year,
j.Month,
j.FileIndex
}
select item;
I think there should be a shorter solution with more performance. Does anyone have a hint for me?
Thank you
You were close. It's not necessary to actually select the grouping key. You can simply select the first item of each group:
var maxFileIndexRecords =
from item in context.Udps
group item by new { item.Guid, item.Year, item.Month }
into gcs
select gcs.OrderByDescending(x => x.FileIndex).FirstOrDefault();

C# List grouping and assigning a value

I have a list of Orders. This list contains multiple orders for the same item, see the table below.
I then want to assign each item that is the same (i.e. ABC) the same block ID. So ABC would have a block ID of 1 & each GHJ would have a block ID of 2 etc. What is the best way of doing this?
Currently I order the list by Order ID and then have a for loop and check if the current Order ID is equal to the next Order ID if so assign the two the same block ID. Is there a better way of doing this using linq or any other approach?
Order ID Block ID
ABC
ABC
ABC
GHJ
GHJ
GHJ
MNO
MNO
You can do this that way, it will assign same blockid for same orderid
var ordered = listOrder.GroupBy(x => x.OrderId).ToList();
for (int i = 0; i < ordered.Count(); i++)
{
ordered[i].ForEach(x=>x.BlockId=i+1);
}
it will group orders by orderid then assign each group next blockid. Note that it won't be done fully in linq, because linq is for querying not changing data.
Always depends of what better means for you in this context.
There are a bunch of possible solutions to this trivial problem.
On top of my head, I could think of:
var blockId = 1;
foreach(var grp in yourOrders.GroupBy(o => o.OrderId))
{
foreach(var order in grp)
{
order.BlockId = blockId;
}
blockId++;
}
or (be more "linqy"):
foreach(var t in yourOrders.GroupBy(o => o.OrderId).Zip(Enumerable.Range(1, Int32.MaxValue), (grp, bid) => new {grp, bid}))
{
foreach(var order in t.grp)
{
order.BlockId = t.bid;
}
}
or (can you still follow the code?):
var orders = yourOrders.GroupBy(o => o.OrderId)
.Zip(Enumerable.Range(1, Int16.MaxValue), (grp, id) => new {orders = grp, id})
.SelectMany(grp => grp.orders, (grp, order) => new {order, grp.id});
foreach(var item in orders)
{
item.order.BlockId = item.id;
}
or (probably the closest to a simple for loop):
Order prev = null;
blockId = 1;
foreach (var order in yourOrders.OrderBy(o => o.OrderId))
{
order.BlockId = (prev == null || prev.OrderId == order.OrderId) ?
blockId :
++blockId;
prev = order;
}
Linq? Yes.
Better than a simple loop? Uhmmmm....
Using Linq will not magically make your code better. Surely, it can make it often more declarative/readable/faster (in terms of lazy evaluation), but sure enough you can make otherwise fine imperative loops unreadable if you try to force the use of Linq just because Linq.
As a side note:
if you want to have feedback on working code, you can ask at codereview.stackexchange.com

C# Linq Select Rows Where ID Equals ID in CSV

What I have is a string of comma separated IDs that I'm receiving from a query string (e.g. 23,51,6,87,29). Alternately, that string could just say "all".
In my Linq query I need a way to say (in pseudo code):
from l in List<>
where l.Id = all_of_the_ids_in_csv
&& other conditions
select new {...}
I'm just not sure how to go about doing that. I'm not even sure what to google to get me going in the right direction. Any pointing in the right direction would be extremely helpful.
I would suggest to split your query in 2 - first part will select by ID, and the select one will select other conditions.
First of all: check if query string contains numbers, or is just all:
var IEnumerable<ListItemType> query = sourceList;
if(queryStringValue != "All")
{
var ids = queryStringValue.Split(new[] { ',' })
.Select(x => int.Parse(x)) // remove that line id item.Id is a string
.ToArray();
query = query.Where(item => ids.Contains(item.Id));
}
from l in query
// other conditions
select new {...}
Because LINQ queries have deffered execution you can build queries like that without performance drawback. Query won't be executed until you ask for results (by ToList call or enumeration).
If you really want it with just one LINQ query:
var idArray = all_of_the_ids_in_csv.Split(',');
from l in List<>
where (all_of_the_ids_in_csv == "All" || idArray.Contains(l.Id))
&& other conditions
select new {...}
The trick is using string.Split
var ids = string.split(rawIdString, ",").ToList();
var objects = ids.Where(id=> /*filter id here */).Select(id=>new { /* id will be the single id from the csv */ });
// at this point objects will be an IEnumerable<T> where T is whatever type you created in the new statement above

Entity Framework generated sql restrict related records

I have the following linq select query that loops round all the 'Places' linked to 'adrianMember' that start with B, I only want to show the PlaceName. I have a navigation association from Member to Place but not from Place to Member.
using (var fdb = new FALDbContext())
{
var adrianMember = fdb.Members.Find(1);
foreach (string s in adrianMember.Places.Where(p=>p.PlaceName.StartsWith("B")).Select(p => p.PlaceName))
{
Console.WriteLine("- " + s);
}
}
I have experimented with various linq syntax too, for example not using Find...
var adrianMember = fdb.Members.Where(m => m.MemberId == 1).FirstOrDefault();
and providing two linq queries, one to retrieve the member and then later retrieve the related places (and hopefully making the EF do some lazy deferred loading) but that still results in very inefficient sql.
using (var fdb = new FALDbContext())
{
//Need the FirstOrDefault otherwise we will return a collection (first or default will return the inner collection
//could have multiple members with multiple places
var members = fdb.Members.Where(m=>m.FirstName == "Bob");
foreach (var member in members)
{
var places = member.Places.Where(p => p.PlaceName.StartsWith("B")).Select(p => p.PlaceName);
foreach (var place in places)
{
Console.WriteLine(place);
}
}
}
The SQL output gets all rows and all columns
exec sp_executesql N'SELECT
[Extent1].[PlaceId] AS [PlaceId],
[Extent1].[PlaceName] AS [PlaceName],
[Extent1].[PlaceLocation] AS [PlaceLocation],
[Extent1].[Member_MemberId] AS [Member_MemberId]
FROM [dbo].[Places] AS [Extent1]
WHERE [Extent1].[Member_MemberId] = #EntityKeyValue1',N'#EntityKeyValue1 int',#EntityKeyValue1=1
Is there a way to restrict the sql to something like
SELECT PlaceName FROM Places WHERE MemberId = 1 AND PlaceName like 'B%'
I have a couple of situations in my project where the above generated sql will make the query too slow (20,000 records per member over 20 columns). Is linq clever enough to make the change if I do have more records?
Try this:
using (var fdb = new FALDbContext())
{
var members = fdb.Members.Where(m=>m.FirstName == "Bob");
foreach (var member in members)
{
fdb.Places.Where(p => p.PlaceName.StartsWith("B") && p.MemberId == member.Id).Select(p => p.PlaceName);
foreach (var place in places)
{
Console.WriteLine(place);
}
}
}
There is a similar question here
After a month away from this problem I thought I'd take a second look...
Firstly, I'm not really sure what I wanted to achieve!!! However, I do seem to have found some interesting and more efficient sql queries for what I wanted.
My first option is to use explicit loading using the Entry & Collection methods. This creates a SQL query to retrieve each corresponding Place record and, importantly, projects the columns I want (just the description) and restricts the rows (those Places beginning with L). This does create many queries though if I have many associated places but I can do this on the fly if I don't know which Places I want to retrieve.
using (var fdb = new FALDbContext())
{
foreach (var member in fdb.Members)
{
var places = fdb.Entry(member)
.Collection(m => m.Places)
.Query()
.Where(p => p.PlaceName.StartsWith("L"))
.Select(p => p.PlaceName);
foreach (var place in places)
{
Console.WriteLine(place);
}
}
}
The second option is to use lazy loading but specify a tightly controlled bit of LINQ to Entities.
This goes to the database once and retrieves just the members I want and projects and restricts both tables and all in one lovely efficient looking sql query!
using (var fdb = new FALDbContext())
{
var myList = fdb.Members
.Where(m => m.GenderShareWithId > 0)
.Select(m => new { m.MemberId, m.DisplayName, Places = m.Places.Where(p => p.PlaceName.StartsWith("L")).Select(p => p.PlaceName) });
foreach (var item in myList)
{
Console.WriteLine(item.DisplayName);
foreach (var place in item.Places)
{
Console.WriteLine(" - " + place);
}
}
}
SELECT
[Extent1].[MemberId] AS [MemberId],
[Extent1].[DisplayName] AS [DisplayName],
[Extent2].[PlaceName] AS [PlaceName]
FROM [dbo].[Members] AS [Extent1]
LEFT OUTER JOIN [dbo].[Places] AS [Extent2]
ON ([Extent1].[MemberId] = [Extent2].[Member_MemberId]) AND ([Extent2].[PlaceName] LIKE N'L%')
WHERE [Extent1].[GenderShareWithId] > 0

Using LINQ to group a list of strings based on known substrings that they will contain

I have a known list of strings like the following:
List<string> groupNames = new List<string>(){"Group1","Group2","Group3"};
I also have a list of strings that is not known in advance that will be something like this:
List<string> dataList = new List<string>()
{
"Group1.SomeOtherText",
"Group1.SomeOtherText2",
"Group3.MoreText",
"Group2.EvenMoreText"
};
I want to do a LINQ statement that will take the dataList and convert it into either an anonymous object or a dictionary that has a Key of the group name and a Value that contains a list of the strings in that group. With the intention of looping over the groups and inner looping over the group list and doing different actions on the strings based on which group it is in.
I would like a data structure that looks something like this:
var grouped = new
{
new
{
Key="Group1",
DataList=new List<string>()
{
"Group1.SomeOtherText",
"Group1.SomeOtherText2"
}
},
new
{
Key="Group2",
DataList=new List<string>()
{
"Group2.EvenMoreText"
}
}
...
};
I know I can just loop through the dataList and then check if each string contains the group name then add them to individual lists, but I am trying to learn the LINQ way of doing such a task.
Thanks in advance.
EDIT:
Just had another idea... What if my group names were in an Enum?
public enum Groups
{
Group1,
Group2,
Group3
}
How would I get that into a Dictionary>?
This is what I am trying but i am not sure how to form the ToDictionary part
Dictionary<Groups,List<string>> groupedDictionary = (from groupName in Enum.GetNames(typeof(Groups))
from data in dataList
where data.Contains(groupName)
group data by groupName).ToDictionary<Groups,List<string>>(...NOT SURE WHAT TO PUT HERE....);
EDIT 2:
Found the solution to the Enum question:
var enumType = typeof(Groups);
Dictionary<Groups,List<string>> query = (from groupName in Enum.GetValues(enumType).Cast<Groups>()
from data in dataList
where data.Contains(Enum.GetName(enumType, groupName))
group data by groupName).ToDictionary(x => x.Key, x=> x.ToList());
That looks like:
var query = from groupName in groupNames
from data in dataList
where data.StartsWith(groupName)
group data by groupName;
Note that this isn't a join, as potentially there are overlapping group names "G" and "Gr" for example, so an item could match multiple group names. If you could extract a group name from each item (e.g. by taking everything before the first dot) then you could use "join ... into" to get a group join. Anyway...
Then:
foreach (var result in query)
{
Console.WriteLine("Key: {0}", result.Key);
foreach (var item in result)
{
Console.WriteLine(" " + item);
}
}
If you really need the anonymous type, you can do...
var query = from groupName in groupNames
from data in dataList
where data.StartsWith(groupName)
group data by groupName into g
select new { g.Key, DataList = g.ToList() };

Categories

Resources