2011-02-05 69 views
3

使用LinQ我想查詢列表並找到重複的人(重複的定義爲 具有相同的姓,名和出生日期),並用字符串「duplicate」標記每個重複人物的 StateOfData屬性,並用字符串「unique」標記每個唯一人員的StateOfData屬性。使用Linq按列表中的多列進行分組並標記所有重複的項目

public Class Person 
{ 
public string PersonFirstName { get; set; } 
public string PersonLastName { get; set; } 
public datetime PersonDateOfBirth { get; set; } 
public string StateOfData{ get; set } 

public Person (string firstName, string lastName, dateTime dateOfBirth,string state) 
{ 
    this.PersonFirstName = firstName; 
    this.PersonLastName = lastName; 
    this.PersonDateOfBirth = dateOfBirth; 
    this.StateOfData = state; 
} 


} 


IList<Person> personsList = new List<Person>(); 
Person pers = new Person("Diane","Jones","1967-01-01",""); 
personsList.add(pers); 
Person pers = new Person("Diane","Jones","1967-01-01",""); 
personsList.add(pers); 
Person pers = new Person("John","Jones","1967-01-01",""); 
personsList.add(pers); 

的人員名單的結果應改爲:

「戴安娜」, 「奇兵」, 「1967年1月1日」, 「重複」
「戴安娜」, 「奇兵」,「1967年-01-01" , 「重複」
「約翰」, 「奇兵」, 「1967年1月1日」, 「獨一無二」

任何幫助,將不勝感激

+0

是C#代碼嗎?你不能寫它,所以它至少可以編譯?它會讓我們的生活更輕鬆。 – Snowbear 2011-02-05 19:19:31

+0

對不起,我把代碼輸入到記事本中,因爲在家裏沒有開發環境 - 認爲代碼很簡單,足以修復,如果不可編譯。謝謝你的回答。週一將在工作中使用。 – Paul 2011-02-06 14:32:31

回答

6
var theLookup = personList 
    .GroupBy(p => new {p.PersonFirstName, p.PersonLastName, p.PersonDateOfBirth}) 
    .ToLookup(g => g.Skip(1).Any() ? "duplicate" : "unique"); 

foreach(var lookupEntry in theLookup) 
{ 
    string stateOfData = lookupEntry.Key; 
    foreach(Person p in lookupEntry.SelectMany(g => g)) 
    { 
    p.StateOfData = stateOfData; 
    } 
} 
相關問題