Consider this example data:
field1 field2
1 100
2 100
3 101
4 102
5 102
6 103
I want to select only the records where the value in field2 occurs only once. An example of the desired return data from the above would be:
field1 field2
3 101
6 103
How would this be done with LINQ to SQL?
— EDIT ——-
Hello all, thank you for your responses. I purposely supplied simplified data to get right to the root of my question. I think all these answers return the desired results based on my example data and I will be marking them all answers as such.
however in my real data scenario, using what I’ve learned from your responses, I have something like this:
var RefinedSource = from a in dSource
group a by a.AssetID into g
where g.Count() == 1
select new
{
AssetID = g.Key,
AssetType = g.Min(a => a.AssetType),
IPInfo = AppUtility.GetIPInfo(g.Key),
Hostname = AppUtility.GetServerName(g.Key),
DeviceID = g.Min(a => a.DeviceID).ToString(),
Environment = AppUtility.GetSolutionAndEnvironmentNames(g.Key),
Manufacturer = g.Min(a => a.Manufacturer),
MakeModel = g.Min(a => a.MakeModel),
Location = g.Min(a => a.Location),
count = g.Count()
};
So I’m concerned about all the .min() calls… I’ve deduced these are necessary because of the grouping? could someone explain why these are needed? In the case of my simple example I don’t see them being an issue, but with my real data there a multiple calls to min() just to be able to include all the field data I need… which doesn’t seem good.
The grouping allows me to test the condition I need (that count to identify duplicate values) but how do I more directly use a condition like this but just access my real underlying data rows directly?
for example, looking at the example I just supplied above, I would like to be able to just use a.FieldName from the original “from a in dSource” part, but you can’t access that after you have introduced “group by”?
again, thanks for the info, I will be marking as answers, however if anyone could explain the need for all the calls to min() (or max, or whatever) I would appreciate it, also, seeing what it looks like with my real data, is this still the way I should go?
I’d double check that this does one SQL call. It should, and if so I’d keep it as here because
Firstis a very commonly used Linq method, and when there’s a few dozen equally good things to use in a given case one should favour the familiar. If it did cause more than one SQL call (again, I’d be surprised), then tryMax()orMin()instead ofFirst().