Reputation: 4677
I have the following Class:
public class Test
{
public string ColumnA { get; set; }
public int ColumnB { get; set; }
public int ColumnC { get; set; }
}
An the following list:
List<Test> testList = new List<Test>()
{
new Test() { ColumnA = "Element 1", ColumnB = 1, ColumnC = 3 },
new Test() { ColumnA = "Element 2", ColumnB = 2, ColumnC = 2 },
new Test() { ColumnA = "Element 3", ColumnB = 1, ColumnC = 3 },
new Test() { ColumnA = "Element 4", ColumnB = 4, ColumnC = 4 },
new Test() { ColumnA = "Element 5", ColumnB = 5, ColumnC = 5 },
new Test() { ColumnA = "Element 6", ColumnB = 7, ColumnC = 0 },
new Test() { ColumnA = "Element 7", ColumnB = 7, ColumnC = 0 }
};
So, I want to select only the unique elements (that the column B and C don't is the same comparing with other elements), that is: "Element 2", "Element 4" and "Element 5".
Obs: I don't want to bring distinct elements, the elements that are repeated I don't want to bring it, both of them.
How can I do that?
Upvotes: 0
Views: 124
Reputation: 102763
Using Linq to select elements that don't have a duplicate:
Test[] noDupes = testList.Where(item =>
!testList.Except(new[] { item }).Any(inner => inner.Equals(item))
).ToArray();
(This assumes you've implemented Equals
on Test
, of course.)
Upvotes: 0
Reputation: 142
One could write
List<Test> data = testList.FindAll(test => test.ColumnB == test.ColumnC);
The method FindAll
is optimized due member of List<T>.FindAll
Upvotes: -1
Reputation: 125630
var results = source.GroupBy(x => new { x.ElementB, x.ElementC })
.Where(g => g.Count() == 1)
.Select(g => g.Single());
Just group using ElementB
and ElementC
properties and take elements from groups that have only one element within it (what means they are unique).
Upvotes: 3
Reputation: 25370
What about lambda
List<Test> answer = testList.Where(t => t.ColumnB == t.ColumnC).ToList();
Upvotes: 0