这是我的清单
int specifiedvalue = 6.5;
名称值
A 6.5
A 6.0
B 6.5
B 6.0
C 7.75
D 7.0
我想从此列表中删除具有相同名称和不同于指定值(6.5)的值的对象,并保留其余部分。
结果应如下:
A 6.5
B 6.5
C 7.75
D 7.0
由于
答案 0 :(得分:1)
internal class NameValue
{
public string Name { get; set; }
public double Value { get; set; }
}
var sourceList = new List<NameValue>
{
new NameValue {Name = "A", Value = 6.5},
new NameValue {Name = "A", Value = 6.0},
new NameValue {Name = "B", Value = 6.5},
new NameValue {Name = "B", Value = 6.0},
new NameValue {Name = "C", Value = 7.75},
new NameValue {Name = "D", Value = 7.0}
};
var result = sourceList.GroupBy(x => x.Name)
.Select(x => new
{
Name = x.Key,
Value = x.Max(y => y.Value)
});
答案 1 :(得分:1)
首先你写道,specifiedValue
的类型是int
。但是vaue是浮点数,您必须将其更改为double
。
我想,你已经宣布了你的课程:
public class Lens
{
public string Name { get; set; }
public double Value { get; set; }
public Lens(string name, double value)
{
Name = name;
Value = value;
}
}
这里我正在初始化对象:
double specidifedValue = 6.5;
List<Lens> pairs = new List<Lens>();
pairs.Add(new Lens("A", 6.5));
pairs.Add(new Lens("A", 6.0));
pairs.Add(new Lens("B", 6.5));
pairs.Add(new Lens("B", 6.0));
pairs.Add(new Lens("C", 7.75));
pairs.Add(new Lens("D", 7.0));
有了这个,首先我发现Name
个在列表中出现过多次。然后选择值为6.5的那些。
var keysMoreThanOne = pairs.GroupBy(x => x.Name)
.Where(x => x.Count() > 1).Select(x => x.Key).ToList();
List<Lens> filteredPairs = pairs
.Where(x => (keysMoreThanOne.Contains(x.Name) && x.Value == specidifedValue)
|| !keysMoreThanOne.Contains(x.Name)).ToList();
结果如您所愿。
<强>更新强>:
var result = new List<Lens>();
var keysMoreThanOne = pairs.GroupBy(x => x.Name).Where(x => x.Count() > 1).Select(x => x.Key).ToList();
if (specidifedValue > 0)
{
result = pairs.Where(x => (keysMoreThanOne.Contains(x.Name) && x.Value == specidifedValue) ||
!keysMoreThanOne.Contains(x.Name)).ToList();
}
else
{
result = pairs.Where(x => (keysMoreThanOne.Contains(x.Name) &&
x.Value == pairs.Where(y=> y.Name==x.Name).OrderByDescending(y=> y.Value).First().Value)
|| !keysMoreThanOne.Contains(x.Name)).ToList();
}