Consultation area
Naor:
I have the following query:
int maxShoeSize = Workers.Where(x => x.CompanyId == 8)
.Max(x => x.ShoeSize);
If workers. Where (x = & gt; x. Companyid = = 8) code> if no workers are found, the above code will throw an exception.
Now the idea is: query can return 0 if it can't be found, but don't throw an exception. How can I modify the query above?
Answer area
Ron K.:
You can use the extension method of IEnumerable defaultifempty() code> to avoid this embarrassment. Refer to the following code.
class Program
{
static void Main(string[] args)
{
List<Worker> Workers = new List<Worker>()
{
new Worker(){ CompanyId=1, CompanyName="tweet", ShoeSize=10 },
new Worker(){ CompanyId=2, CompanyName="google", ShoeSize=20 },
};
int maxShoeSize = Workers.Where(x => x.CompanyId == 8)
.Select(x => x.ShoeSize)
.DefaultIfEmpty(0)
.Max();
Debug.WriteLine($"maxShoeSize={maxShoeSize}");
}
}
class Worker
{
public int CompanyId { get; set; }
public string CompanyName { get; set; }
public int ShoeSize { get; set; }
}
Output results:
maxShoeSize=0
Of course, the above 0 code> is not necessary. You can change it to any other number.
CptRobby:
Although the plan provided by the man upstairs can work normally, it doesn't look very eye-catching. It can be transformed into the following one.
int maxShoeSize = Workers.Where(x => x.CompanyId == 8)
.Select(x => (int?)x.ShoeSize)
.Max() ?? 0;
Does the code look a little lengthy?The best way is to customize a extension method code>, as shown in the following code:
public static int MaxOrDefault<T>(this IQueryable<T> source, Expression<Func<T, int?>> selector, int nullValue = 0)
{
return source.Max(selector) ?? nullValue;
}
For simplicity, this extension only deals with the int code> type. You can change it to any type, such as: (long, double,...), and then you can continue to reform the caller.
int maxShoeSize = Workers.Where(x => x.CompanyId == 8).MaxOrDefault(x => x.ShoeSize);
I hope my answer can help more people.
Comment area
Xiaobian never dares to do Max on the empty collection code>, after all, it's not once or twice, so every time we judge whether there is a value in the collection in advance, and then execute
Max code>, we didn't expect that there are magic extension methods
defaultifempty code> and
empty type code> that can help us to do it, and we all forget about sensory science????????????.
Read More:
- Default constructor cannot handle exception type FileNotFoundException thrown by implicit super cons
- Solve the unexpected end of stream exception thrown by jedis
- Exception on start hive: caused by: java.net.noroutetohostexception: no route to host
- A stopiteration exception is thrown after Python next() completes
- How to avoid OrderSend Error 130 in MT4
- Web Crawler: How to get the data in the web page and disguise the header, disguise as a browser to visit many times, avoid a single visit leading to IP blocked
- java.util.Collections.max() [How to Use]
- [resolved] exception java.net.ConnectException : Error opening socket to server Connection timed out.
- How to Fix error performing isolated work; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarE
- Caused by: java.net.SocketException : connection reset or caused by: java.sql.SQLRecoverableException solve
- How to handle exception in springboot
- mkdir: Call From hadoop102/192.168.6.102 to hadoop102:8020 failed on connection exception: java.net.
- 【Q&A】Failed to start LSB: Bring up/down networking
- Ngixn exception net:: err_ HTTP2_ PROTOCOL_ ERROR 200
- Why can’t Scala shell enter Q to exit
- Chrome console reports Failed to load resource: net::ERR_BLOCKED_BY_CLIENT one of the solutions
- ASP.NET How to deal with “unexpected character” when writing code
- How to Fix java.net.ConnectException: Connection refused: connect
- ansible Q&A: Failed to connect to the host via ssh: ssh_exchange_identification and Authentication or per
- Methods to avoid fail to allocate bitmap errors in pyplot