문제

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