I am using c# framework 3.5 ..
my class here
public class KonumBilgisi
{
public string Enlem { get; set; }
public string Boylam { get; set; }
public string KonumAdi { get; set; }
public DateTime Tarih { get; set; }
public byte SucTuruId { get; set; }
}
I have a list
List konumlar;
well, I want to get items that equal their enlem and boylam variables each other..
As you see on the photo below
I want to compate enlem and boylam and if its the equal I want to get them to different list..
I can do that with a loop but want to use LINQ but i couldnt do that. I used groupby but it doesnt wrong..
var distinctList = konumlar.GroupBy(x => x.Enlem)
.Select(g => g.First())
.ToList().GroupBy(s=>s.Boylam).Select(g => g.First())
.ToList();
EDIT Actually I couldnt explain my quesion well..
maybe distinct is not right word.. I want to seperate items which are equals each other..
such as:
I will take pendik items in one list and others will be in konumlar but pendik items will be removed from konumlar list
EDIT 2
Okay I want to seperate the list like that
You are almost there - rather than using two separate GroupBy
calls, use a single one, with a two-part key:
var distinctList = konumlar
.GroupBy(s => new {s.Enlem, s.Boylam})
.Select(g => g.First())
.ToList();
EDIT : To get all items except the ones with duplicates, modify the query as follows:
var noPendiks = konumlar
.GroupBy(s => new {s.Enlem, s.Boylam})
.Where(g => g.Count() == 1)
.Select(g => g.Single()) // You know there's only one
.ToList();
The above will give you all items except the "pendik" ones. To get only the "pendik"s, use the query below:
var pendiks = konumlar
.GroupBy(s => new {s.Enlem, s.Boylam})
.Where(g => g.Count() > 1)
.SelectMany(g => g)
.ToList();
You can use the Distinct() Linq function, however, that does only work identical items. In case you want a DistinctBy() you can create a LinqExtensions class with a DistinctBy() method.
Here's one which I use quite common:
/// <summary>
/// Provides common extension methods on LINQ members.
/// </summary>
public static class LinqExtensions
{
#region Members
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
HashSet<TKey> seenKeys = new HashSet<TKey>();
foreach (TSource element in source)
{
if (seenKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
#endregion Members
}
Use it as:
var distinctList = konumlar.DistinctBy(x => x.property && x.property2 && ...);
Kind regards
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With