Clean some properties value in List with Linq based on a value of the list

I have an object " MyObject " with the properties (all string): " PropA ", " PropB " and " PropC ".

var List = new List();

I add some object in this list with the following value :

List.Add(new MyObject { PropA = "AA", PropB = "1", PropC = "TT"});
List.Add(new MyObject { PropA = "AA", PropB = "1", PropC = "TT"});
List.Add(new MyObject { PropA = "AA", PropB = "1", PropC = "TT"});

List.Add(new MyObject { PropA = "BB", PropB = "1", PropC = "TT"});
List.Add(new MyObject { PropA = "BB", PropB = "1", PropC = "TT"});

With linq, I'd like for each different " PropA " keep the first record but set to string.Empty the other. The result I'd like is a List with these values :

MyObject { PropA = "AA", PropB = "1", PropC = "TT"}
MyObject { PropA = "", PropB = "", PropC = "TT"}
MyObject { PropA = "", PropB = "", PropC = "TT"}
MyObject { PropA = "BB", PropB = "1", PropC = "TT"}
MyObject { PropA = "", PropB = "", PropC = "TT"}

I did with foreach but it's may be a bit cleaner in Linq, but the order of the result must be kept.


This would work for the specific case:

var list = 
 List.GroupBy(x => x.PropA)
        .SelectMany(grp => new MyObject[] { grp.First() }
        .Concat(grp.Skip(1)
          .Select(x => { x.PropA = String.Empty; x.PropB = String.Empty; return x; } )
           )
         );

LinqPad result:

linqpad截图

As a side note, I don't think using Linq in this case is justified, it doesn't make the code faster or cleaner. One must use the available tools to write better, more performant, or cleaner code, but in this case, I don't think this is better than a foreach (at least a well thought foreach , and not a brute force one) in any possible way.


这个怎么样:

    var result = List.GroupBy(prop => prop.PropA)
        .SelectMany(group => new [] { group.First() }.Concat(group.Skip(1).Select(x => { x.PropA = x.PropB = ""; return x; }))).ToList();

var groups = List.GroupBy(obj => obj.PropA);
foreach (var group in groups)
{
    foreach (var item in group.Skip(1))
    {
        item.PropA = "";
        item.PropB = "";
    }
}
链接地址: http://www.djcxy.com/p/51358.html

上一篇: 我如何使用Linq从对象列表中获取唯一属性列表?

下一篇: 根据列表的值清理List with Linq中的某些属性值