Материал из .Net Framework эксперт
A query to extract strings containing the letter "a", sorted by length and converted to uppercase
using System;
using System.Collections.Generic;
using System.Linq;
class LinqDemo {
static void Main() {
string[] names = { "J", "P", "G", "Pa" };
IEnumerable<string> query =
from n in names
where n.Contains("a")
orderby n.Length
select n.ToUpper();
foreach (string name in query) Console.Write(name + "/");
}
}
Contains with IEqualityComparer
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MyStringifiedNumberComparer : IEqualityComparer<string> {
public bool Equals(string x, string y) {
return (Int32.Parse(x) == Int32.Parse(y));
}
public int GetHashCode(string obj) {
return Int32.Parse(obj).ToString().GetHashCode();
}
}
public class MainClass {
public static void Main() {
string[] stringifiedNums = {"001", "49", "017", "0080", "00027", "2" };
bool contains = stringifiedNums.Contains("2",new MyStringifiedNumberComparer());
Console.WriteLine(contains);
}
}
Contains with predicate returned false
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
public static void Main() {
string[] presidents = {"A", "H", "a", "H", "over", "Jack"};
bool contains = presidents.Contains("G");
Console.WriteLine(contains);
}
}
Contains with string value
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MainClass {
public static void Main() {
string[] presidents = {"G", "H", "a", "H", "over", "Jack"};
bool contains = presidents.Contains("H");
Console.WriteLine(contains);
}
}
Contains with string value and IEqualityComparer
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MyStringifiedNumberComparer : IEqualityComparer<string> {
public bool Equals(string x, string y) {
return (Int32.Parse(x) == Int32.Parse(y));
}
public int GetHashCode(string obj) {
return Int32.Parse(obj).ToString().GetHashCode();
}
}
public class MainClass {
public static void Main() {
string[] stringifiedNums = {"001", "49", "017", "0080", "00027", "2" };
bool contains = stringifiedNums.Contains("000271",new MyStringifiedNumberComparer());
Console.WriteLine(contains);
}
}
Use Contains to check the existance of an element
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Linq;
public class MainClass{
public static void Main(){
int[] numbers = { 2, 6, 1, 56, 102 };
Console.WriteLine("Is there the number 102?");
Console.Write(numbers.Contains(102) ? "Yes, there is" : "No, there isn"t");
}
}