我試圖List<Person>根據Name屬性找到 a 的不同名稱。對于每個不同的名稱,我想創建一個具有相同名稱屬性的新物件,并且所有其他屬性都為空。我如何有效地做到這一點?
人類。
public class Person
{
public string Name { get; set; }
public string Country { get; set; }
}
程式.cs
List<Person> personList = new List<Person>();
var p1 = new Person()
{
Name = "John",
Country = "USA"
};
var p2 = new Person()
{
Name = "John",
Country = "China"
};
var p3 = new Person()
{
Name = "Bob",
Country = "Italy"
};
var p4 = new Person()
{
Name = "Bob",
Country = "Brazil"
};
var p5 = new Person()
{
Name = "Bob",
Country = "Canada"
};
personList.Add(p1);
personList.Add(p2);
personList.Add(p3);
personList.Add(p4);
personList.Add(p5);
目的是在同一個串列中添加一個“John”和一個“Bob”(因為它們具有不同的名稱),并將國家屬性作為空字串。
uj5u.com熱心網友回復:
使用 Linq 查詢可以很容易地找到所有不同的Name值:
// first use .GroupBy to group everything by the Name property
// and then select a new Person for each grouping of Name
Person[] unique = personList.GroupBy(x => x.Name)
.Select(x => new Person{Name = x.Key})
.ToArray();
創建新集合后;將它們添加到現有集合中:
personList.AddRange(unique);
編輯以用于 .Disinct
或者,您可以從 Linq.Distinct()方法獲取不同的名稱值,而不是使用該.GroupBy()方法,但您需要選擇.Name屬性以獲取 OOB 不同的比較器:
Person[] unique = personList.Select(x => x.Name)
.Distinct()
.Select(x => new Person{Name = x})
.ToArray();
personList.AddRange(unique);
使用Distinct需要使用內置的IEqualityComparer,或者IEqualityComparer在多載中提供自定義。簡單地傳入物件本身是無效的,除非物件實作IEqualityComparer. 在這種情況下,選擇將使用內置的Name屬性并呼叫或使用第一個示例中的方法更容易。.DistinctIEqualityComparer.GroupBy
uj5u.com熱心網友回復:
使用 linq 的 Distinct 方法(https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.distinct?view=net-5.0):
public class Person
{
public string Name { get; set; }
public string Country { get; set; }
}
// Program.cs
List<Person> personList = new List<Person> ();
var p1 = new Person ()
{
Name = "John",
Country = "USA"
};
var p2 = new Person ()
{
Name = "John",
Country = "China"
};
var p3 = new Person ()
{
Name = "Bob",
Country = "Italy"
};
var p4 = new Person ()
{
Name = "Bob",
Country = "Brazil"
};
var p5 = new Person ()
{
Name = "Bob",
Country = "Canada"
};
personList.Add(p1);
personList.Add (p2);
personList.Add (p3);
personList.Add (p4);
personList.Add (p5);
var personsWithDistinctNameInPersonList = personList.Select(p => p.Name).Distinct()
.Select(n => new Person {
Name = n,
}).ToList();
personList.AddRange(personsWithDistinctNameInPersonList);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/340363.html
標籤:C#
