鉴于以下课程
public class Foo
{
public int FooId { get; set; }
public string FooName { get; set; }
public override bool Equals(object obj)
{
Foo fooItem = obj as Foo;
if (fooItem == null)
{
return false;
}
return fooItem.FooId == this.FooId;
}
public override int GetHashCode()
{
// Which is preferred?
return base.GetHashCode();
//return this.FooId.GetHashCode();
}
}
Run Code Online (Sandbox Code Playgroud)
我已经覆盖了该Equals方法,因为它Foo代表了Foos表的一行.哪个是覆盖的首选方法GetHashCode?
覆盖为什么重要GetHashCode?
class Program
{
static void Main(string[] args)
{
List<Book> books = new List<Book>
{
new Book
{
Name="C# in Depth",
Authors = new List<Author>
{
new Author
{
FirstName = "Jon", LastName="Skeet"
},
new Author
{
FirstName = "Jon", LastName="Skeet"
},
}
},
new Book
{
Name="LINQ in Action",
Authors = new List<Author>
{
new Author
{
FirstName = "Fabrice", LastName="Marguerie"
},
new Author
{
FirstName = "Steve", LastName="Eichert"
},
new Author
{
FirstName = "Jim", LastName="Wooley"
},
}
}, …Run Code Online (Sandbox Code Playgroud) 通常我必须编写一个循环,它必须特殊情况下集合中的第一个项目,代码似乎永远不应该是清晰的.
如果没有重新设计C#语言,那么编写这些循环的最佳方法是什么?
// this is more code to read then I would like for such a common concept
// and it is to easy to forget to update "firstItem"
foreach (x in yyy)
{
if (firstItem)
{
firstItem = false;
// other code when first item
}
// normal processing code
}
// this code is even harder to understand
if (yyy.Length > 0)
{
//Process first item;
for (int i = 1; i < yyy.Length; i++)
{
// process …Run Code Online (Sandbox Code Playgroud) 以下检查字符串数组中的所有值是否相等,忽略大小写
string [] StringArray = new string[]{"xxx","xXx","Xxx"};
bool ValuesAreEqual = false;
for(int i= 0;i<StringArray.Length;i++)
{
if(i>=1)
{
ValuesAreEqual = StringArray[0].Equals(StringArray[i],StringComparison.InvariantCultureIgnoreCase);
if(!ValuesAreEqual)
{
break;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我怎么能用LINQ写这个?