LINQ query to return distinct field values from list of objects

class obj
{
int typeId; //10 types  0-9
string uniqueString; //this is unique
}

Assume there is a list with 100 elements of objs, but only 10 unique typeIDs.

Is it possible to write a LINQ query that returns the 10 unique ints from the list of objs?

283733 次浏览
objList.Select(o=>o.typeId).Distinct()

当然,用 Enumerable.Distinct

Given a collection of obj (e.g. foo), you'd do something like this:

var distinctTypeIDs = foo.Select(x => x.typeID).Distinct();

I think this is what your looking for:

    var objs= (from c in List_Objects
orderby c.TypeID  select c).GroupBy(g=>g.TypeID).Select(x=>x.FirstOrDefault());

Similar to this 用 LINQ 返回一个不同的 IQueryable? ?

假设您想要完整的对象,但是只想通过 typeID处理不同的对象,那么 LINQ 中没有内置任何东西来使这个过程变得容易。(如果 just需要 typeID值,那么很容易将 Select投影到这个值,然后使用普通的 Distinct调用。)

MoreLINQ中我们有 DistinctBy操作符,你可以使用:

var distinct = list.DistinctBy(x => x.typeID);

不过这只适用于 LINQ to Objects。

你可以使用分组或者查找,只是有点烦人而且效率低下:

var distinct = list.GroupBy(x => x.typeID, (key, group) => group.First());

我想把一个特定的数据绑定到下拉列表,它应该是独立的。 我做了以下几件事:

List<ClassDetails> classDetails;
List<string> classDetailsData = classDetails.Select(dt => dt.Data).Distinct.ToList();
ddlData.DataSource = classDetailsData;
ddlData.Databind();

See if it helps

If just want to user pure Linq, you can use groupby:

List<obj> distinct =
objs.GroupBy(car => car.typeID).Select(g => g.First()).ToList();

If you want a method to be used all across the app, similar to what 莫林克 does:

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.Contains(keySelector(element)))
{
seenKeys.Add(keySelector(element));
yield return element;
}
}
}

使用此方法仅使用 Id 属性查找不同的值,您可以使用:

var query = objs.DistinctBy(p => p.TypeId);

您可以使用多个属性:

var query = objs.DistinctBy(p => new { p.TypeId, p.Name });

如果只想使用 Linq,可以重写 EqualsGetHashCode方法。

产品类别:

public class Product
{
public string ProductName { get; set; }
public int Id { get; set; }




public override bool Equals(object obj)
{
if (!(obj is Product))
{
return false;
}


var other = (Product)obj;
return Id == other.Id;
}


public override int GetHashCode()
{
return Id.GetHashCode();
}
}

主要 方法:

static void Main(string[] args)
{


var products = new List<Product>
{
new Product{ ProductName="Product 1",Id = 1},
new Product{ ProductName="Product 2",Id = 2},
new Product{ ProductName="Product 4",Id = 5},
new Product{ ProductName="Product 3",Id = 3},
new Product{ ProductName="Product 4",Id = 4},
new Product{ ProductName="Product 6",Id = 4},
new Product{ ProductName="Product 6",Id = 4},
};


var itemsDistinctByProductName = products.Distinct().ToList();


foreach (var product in itemsDistinctByProductName)
{
Console.WriteLine($"Product Id : {product.Id} ProductName : {product.ProductName} ");
}


Console.ReadKey();
}