I have a class like

public class MyClass
{
  public float Consumed { get; set;}
  public int RequiredValue { get; set;}
}

A list of this class

List<MyClass> list

already has some items of type MyClass containing the "RequiredValue" say 3,5,6,8 and 10 and corresponding values in "Consumed" property. I find the missing values in the Range of 1 to 10 using the following code:

var missingValues = Enumerable.Range(1, 10).Except(list.Select(p1 => p1.RequiredValue));

I want to add items in the "list" using Linq such that the new items have missing values in the "RequiredValue" and "Consumed" as 0.

有帮助吗?

解决方案

This will generate your objects and add them to collection (you don't need to initialize Consumed property, because it already will have zero as default value):

list.AddRange(Enumerable.Range(1, 10)
                        .Except(list.Select(m => m.RequiredValue))
                        .Select(i => new MyClass() { RequiredValue = i } );
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top