I saw a question on the forum today, which is described as follows:
I have a student. CS model.
-
class student{public string Sname{get;set;}public int Money{get;set;}}
Existing collection
-
Ilist <student> List = new list <student> (); Student S1 = new student {sname = "Stephen Chow", 60 }; student S2 = new student {sname = "Andy Lau", 80 };
--------------------------------------------------------
My intention is as follows:
When I add another person to the List, such as adding {"Wu MengDa", 50}, the set is added normally.
But when I add another Stephen Chow {"Stephen Chow", 10}, the final result is {"Stephen Chow", 70} because the list already has Stephen Chow}
In general, when the same person is met, the money is added, and the number of sets remains unchanged.
I can use the C # Extension Method for implementation.
Now the code is recorded here for later viewing
Static class extensions <br/>{< br/> internal static void addstudent (This list <student> list, student item) <br/> {<br/> Student temp = List. singleordefault (S => S. sname = item. sname); <br/> If (temp = NULL) list. add (item); <br/> else temp. money + = item. money; <br/>}< br/> class student <br/>{< br/> Public String sname {Get; set ;} <br/> Public int money {Get; Set ;}< br/>}< br/> Public partial class csstest: system. web. UI. page <br/>{< br/> protected void page_load (Object sender, eventargs e) <br/>{< br/> var list = new list <student> (); <br/> list. addstudent (New Student {sname = "Stephen Chow", money = 60}); <br/> list. addstudent (New Student {sname = "Andy Lau", money = 80}); <br/> list. addstudent (New Student {sname = "Stephen Chow", money = 10}); <br/> list. foreach (L => response. write (L. sname + "" + L. money); <br/>/* <br/> * result: <br/> * Stephen Chow 70 <br/> * Andy Lau 80 <br/> */<br/>}
Use extension methods
My personal experience is convenient because vs smart sensing can also perceive
Note that the small icons of this extension method are different from those of others.
Msdn reference: http://msdn.microsoft.com/zh-cn/library/vstudio/bb383977.aspx