Linq select subgroup - linq

I have the following in my db table:
- MailingId | GroupName | ServiceId
- 1 | group1 | 3
- 2 | group1 | 5
- 3 | group1 | 8
- 4 | group2 | null
- 5 | group3 | null
...
In my view i have 2 groups of checkboxes:
1) (services) with id's 3,5,8 (serviceId).
2) and a list of checkboxes for mailing groups (group1, group2, group3)
I need to select the following using LINQ:
Select rows that I have selected in ServiceId checkbox list PLUS any other. For example if I check off ServiceId's (3 and 5) and group "Group3" then my output would be rows MailingId: 1, 3 and 5. HOWEVER, if I select ANY service from (first group of checkboxes) AND DO NOT select "Group1" from mailing group checkboxes then rows with Group1 SHOULD NOT be in the output.
I'm using EF4. Please help.
Thanks

The 2 arrays would be the selections that are posted from your view
int[] selectedservices = {3,5};
string[] selectedgroups = {"group3"};
using (Model model = new Model())
{
bool b = selectedservices.Contains(1);
var mailinglists = from m in model.MalingSet
where selectedgroups.Contains(m.GroupName)
&& ((m.ServiceId.HasValue && selectedservices.Contains(m.ServiceId.Value)) || m.ServiceId.HasValue == false)
select m.MailingId;
}

Try something like this.
var mailingGroup =
from m in Mailings
where m.ServiceId != null // or whatever other condition
group m by m.GroupName into g
select new
{
groupName = g.Key,
mailings = g
};

It's a Where clause no?
var a = new {m = 1, g = "group1", sid = 3};
var b = new {m = 2, g = "group1", sid = 5};
var c = new {m = 3, g = "group1", sid = 8};
var d = new {m = 4, g = "group2", sid = 0};
var e = new {m = 5, g = "group3", sid = 0};
var l = new List<dynamic>{a,b,c,d,e};
l.Where(it => ( new ArrayList{3, 5}).Contains(it.sid)
|| (new ArrayList{1, 5}).Contains(it.m)).Dump();
http://www.linqpad.net/

Related

linq query to list that adds position of result

I have the linq query that produces the result below:
var result = from x in model.SITEs
where x.SiteId == homeSite
select new { x.SiteId,
x.SiteAlloc1,
x.SiteAlloc2,
x.SiteAlloc3,
x.SiteAlloc4 });
SiteId SiteAlloc1 SiteAlloc2 SiteAlloc3 SiteAlloc4
======================================================
1 5 3 2 4
But what I need is something more like this, where the Rank is the position of the SiteId in the result.
SiteId Rank
==================
1 1
2 4
3 3
4 5
5 2
var result = from x in model.SITEs
where x.SiteId == homeSite
select new { x.SiteId,
x.SiteAlloc1,
x.SiteAlloc2,
x.SiteAlloc3,
x.SiteAlloc4 }).
Select((t,u) => new {
SiteId = t.SiteId,
SiteAlloc1 = t.SiteAlloc1,
SiteAlloc2 = t.SiteAlloc2,
SiteAlloc3 = t.SiteAlloc3,
SiteAlloc4 = t.SiteAlloc4,
Rank = u + 1));
Where u is the index (0 based, that's why I added 1), or in your case the rank and t is the selected object

Linq FirstOrDefault List inside a query

I have this linq query
var numberGroups =
from n in VISRUBs.Where(a => a.VISANA.VISITE.DATEVIS <= d && a.VISANA.VISITE.PANUM == p)
group n by n.RUBRIQUE into g
select new {
RemainderCHAPLIB = g.Key.ANALYSE.CHAPITRE.LIBELLE,
RemainderLIB = g.Key.LIBELLE,
RemainderRUNUM = g.Key.RUNUM,
vals = from vlist in g.OrderByDescending(a=>a.VISANA.VISITE.DATEVIS)
select vlist.VALEUR
};
which gives me this result in Linqpad
What I want is to select the first and second item from the last field (vals) which is a List<string>.
I have tried this:
var numberGroups =
from n in VISRUBs.Where(a => a.VISANA.VISITE.DATEVIS <= d && a.VISANA.VISITE.PANUM == p)
group n by n.RUBRIQUE into g
select new {
RemainderCHAPLIB = g.Key.ANALYSE.CHAPITRE.LIBELLE,
RemainderLIB = g.Key.LIBELLE,
RemainderRUNUM = g.Key.RUNUM,
vals = from vlist in g.OrderByDescending(a => a.VISANA.VISITE.DATEVIS)
select vlist.VALEUR
};
var lst = from n in numberGroups
select new
{
RemainderCHAPLIB = n.RemainderCHAPLIB,
RemainderLIB = n.RemainderLIB,
RemainderRUNUM = n.RemainderRUNUM,
VAL = n.vals.FirstOrDefault()
};
but it didn't work, I got an exception:
Dynamic SQL ErrorSQL error code = -104Token unknown - line 54, column 1OUTER
found it !
var lst = from n in numberGroups.ToList()
select new
{
RemainderCHAPLIB = n.RemainderCHAPLIB,
RemainderLIB = n.RemainderLIB,
RemainderRUNUM = n.RemainderRUNUM,
VAL = n.vals.FirstOrDefault(),
ANT = n.vals.Skip(1).FirstOrDefault()
};

LINQ filtering on a Dictionary<string, IList<string>>

I have code similar to this:
var dict = new Dictionary<string, IList<string>>();
dict.Add("A", new List<string>{"1","2","3"});
dict.Add("B", new List<string>{"2","4"});
dict.Add("C", new List<string>{"3","5","7"});
dict.Add("D", new List<string>{"8","5","7", "2"});
var categories = new List<string>{"A", "B"};
//This gives me categories and their items matching the category list
var result = dict.Where(x => categories.Contains(x.Key));
Key Value
A 1, 2, 3
B 2, 4
What I would like to get is this:
A 2
B 2
So the keys and just the values that are in both lists. Is there a way to do this in LINQ?
Thanks.
Easy peasy:
string key1 = "A";
string key2 = "B";
var intersection = dict[key1].Intersect(dict[key2]);
In general:
var intersection =
categories.Select(c => dict[c])
.Aggregate((s1, s2) => s1.Intersect(s2));
Here, I'm utilizing Enumerable.Intersect.
A somewhat dirty way of doing it...
var results = from c in categories
join d in dict on c equals d.Key
select d.Value;
//Get the limited intersections
IEnumerable<string> intersections = results.First();
foreach(var valueSet in results)
{
intersections = intersections.Intersect(valueSet);
}
var final = from c in categories
join i in intersections on 1 equals 1
select new {Category = c, Intersections = i};
Assuming we have 2 and 3 common to both lists, this will do the following:
A 2
A 3
B 2
B 3

Dynamic linq - Group by interval (DateTime, Numeric)

I search everywhere and didn`t find anwser for this question. I want to group by intervals (DateTime, Numeric) in Dynamic linq (the data will be crated dynamically so i must use dynamic linq)
Lets assume that we have such data:
ID|Date|Price
1|2010-11-01|100
2|2010-11-01|120
3|2010-11-02|50
4|2010-12-01|30
5|2010-12-01|220
6|2011-01-01|400
How to get this data grouped by like this
-(Group by Day) following groups
->2010-11-01 = 2 elements
->2010-11-02 = 1 elements
->2010-12-01 = 2 elements
->2011-01-01 = 1 elements
-(Group by Month) following groups
->2010-11 = 3 elements
->2010-12 = 2 elements
->2011-01 = 1 elements
-(Group by Quarter) following groups
->2010 q.03 = 5 elements
->2011 q.01 = 1 elements
-(Group by Year) following groups
->2010 = 5 elements
->2011 = 1 element
-(Group by Price (From 0, Each 50)) following groups
-> <0-50) = 1 elements
-> <50-100) = 1 elements
-> <100-150) = 2 elements
-> <200-250) = 1 elements
-> <400-450) = 1 elements
-(ideally it would be Group by Price (From 0-50,From 50-150, From 150-500)) following groups
-> <0-50) = 1 elements
-> <50-150) = 3 elements
-> <150-500) = 2 elements
Any Ideas? I stress again - it must be DYNAMIC LINQ or eventually some sophisticated lambda expression? I should been able to "group" it by column name that will be in string. e.g.
GroupBy("Date"), GroupBy("Price");
Here's how to do it:
For instance:
Group by Month
public Item[] data =
{
new Item { Date = new DateTime(2011, 11, 6), Price = 103, Name = "a" },
new Item { Date = new DateTime(2011, 11, 16), Price = 110, Name = "b" },
new Item { Date = new DateTime(2011, 12, 4), Price = 200, Name = "c" },
new Item { Date = new DateTime(2011, 12, 4), Price = 230, Name = "d" },
new Item { Date = new DateTime(2012, 1, 15), Price = 117, Name = "e" }
};
var groups = data.AsQueryable().GroupBy("Date.Month", "it").Cast<IGrouping<int, Item>>();
You can use "Date.Day" and "Date.Year" and for something like a price range you could use a function which maps everything in the range onto the same value e.g. using integer division "(it.Price / 50)"

Using GroupBy, Count and Sum in LINQ Lambda Expressions

I have a collection of boxes with the properties weight, volume and owner.
I want to use LINQ to get a summarized list (by owner) of the box information
e.g.
**Owner, Boxes, Total Weight, Total Volume**
Jim, 5, 1430.00, 3.65
George, 2, 37.50, 1.22
Can someone show me how to do this with Lambda expressions?
var ListByOwner = list.GroupBy(l => l.Owner)
.Select(lg =>
new {
Owner = lg.Key,
Boxes = lg.Count(),
TotalWeight = lg.Sum(w => w.Weight),
TotalVolume = lg.Sum(w => w.Volume)
});
var q = from b in listOfBoxes
group b by b.Owner into g
select new
{
Owner = g.Key,
Boxes = g.Count(),
TotalWeight = g.Sum(item => item.Weight),
TotalVolume = g.Sum(item => item.Volume)
};
var boxSummary = from b in boxes
group b by b.Owner into g
let nrBoxes = g.Count()
let totalWeight = g.Sum(w => w.Weight)
let totalVolume = g.Sum(v => v.Volume)
select new { Owner = g.Key, Boxes = nrBoxes,
TotalWeight = totalWeight,
TotalVolume = totalVolume }

Resources