开发者

Get a distinct list of ids from IEnumerable<T>

开发者 https://www.devze.com 2023-01-09 21:18 出处:网络
I have an IEnumerable that I want to get all the distinct MaterialIDs.I have code that is working but I was wondering if there is a better way possible using LINQ.Here\'s the code I have:

I have an IEnumerable that I want to get all the distinct MaterialIDs. I have code that is working but I was wondering if there is a better way possible using LINQ. Here's the code I have:

    private IEnumerable<int> GetDistinctMaterialIDs(IEnumerable<TankReading> tankReadings)
    {
        var distinctMaterialIDs = new List<int>();
        foreach (var tankReading in tankReadings)
        {
            if (!distinctMaterialIDs.Contains(tankReading.MaterialID))
            {
                distinctMaterialIDs.Add(tankReadi开发者_如何学编程ng.MaterialID);
            }
        }
        return distinctMaterialIDs;
    }

Any help would be appreciated as I am learning how LINQ can help me.


tankReadings.Select(o => o.MaterialID).Distinct();
0

精彩评论

暂无评论...
验证码 换一张
取 消